【发布时间】:2019-07-17 18:36:25
【问题描述】:
我正在进行 API 调用,但有时响应中没有某些字段。如果我遇到这些响应之一,我的脚本会按预期抛出 KeyError,但随后会完全跳出 for 循环。有没有办法让它简单地跳过错误的输出并继续循环?
我考虑过尝试将我正在搜索的所有字段放入一个列表中,并在遇到缺失字段时使用 continue 语句对其进行迭代,以保持迭代继续进行,但是 1) 看起来很麻烦 2)我在输出中有多个级别的迭代。
try:
for item in result["results"]:
print(MAJOR_SEP) # Just a line of characters separating the output
print("NPI:", item['number'])
print("First Name:", item['basic']['first_name'])
print("Middle Name:", item['basic']['middle_name'])
print("Last Name:", item['basic']['last_name'])
print("Credential:", item['basic']['credential'])
print(MINOR_SEP)
print("ADDRESSES")
for row in item['addresses']:
print(MINOR_SEP)
print(row['address_purpose'])
print("Address (Line 1):", row['address_1'])
print("Address (Line 2):", row['address_2'])
print("City:", row['city'])
print("State:", row['state'])
print("ZIP:", row['postal_code'])
print("")
print("Phone:", row['telephone_number'])
print("Fax:", row['fax_number'])
print(MINOR_SEP)
print("LICENSES")
for row in item['taxonomies']:
print(MINOR_SEP)
print("State License: {} - {}, {}".format(row['state'],row['license'],row['desc']))
print(MINOR_SEP)
print("OTHER IDENTIFIERS")
for row in item['identifiers']:
print(MINOR_SEP)
print("Other Identifier: {} - {}, {}".format(row['state'],row['identifier'],row['desc']))
print(MAJOR_SEP)
except KeyError as e:
print("{} is not defined.".format(e))
【问题讨论】:
-
将
try/except放在每个循环中,而不是包装整个代码 -
我想过,但这就像 25 个单独的 try-except 块。我希望有一个更好的方法,我只是没有考虑。
-
这似乎很难帮助,因为这真的取决于我只能看到 3
fors -
所以,你说的是对每个部分使用 try-except 块,而不是每行输出。
-
您可以编写一个单独的打印函数,并让该函数管理调用数据时发生的错误,或者类似的东西。