【问题标题】:Counting errors and continue in a loop [duplicate]计算错误并循环继续[重复]
【发布时间】:2021-07-22 15:17:17
【问题描述】:

我有一些 python 代码一次发送数百个 API 请求,个别请求中的格式化偶尔会出现 HttpError 失败,但我不希望这停止整个过程。

为了实现这一点,我在 if 语句中添加了一个例外:

def update_conversions(service):

  for req in request_bodies:
    try:
      request = service.conversion().update(body=req)
    except Exception:
      pass

我想更新此代码以获得失败的数量或请求的可行性,同时仍继续循环,如何更新我的代码以将 http 错误计数分配给变量?

【问题讨论】:

  • 添加一个计数器并在except中增加它?

标签: python


【解决方案1】:

这应该可以解决问题:

def update_conversions(service):
  total_failed_requests = 0

  for req in request_bodies:
    try:
      request = service.conversion().update(body=req)
    except Exception:
      total_failed_requests += 1
      print(f"A request has failed, total: {total_failed_requests}")

【讨论】:

  • 谢谢,我还需要pass吗?
  • pass 表示do nothing。由于我们正在执行except语句中的其他指令,因此不再需要pass
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-07
  • 1970-01-01
相关资源
最近更新 更多