我试图从API中提取数据,我希望收到KeyError和IndexError,所以我使用try / except函数来捕获它们。我首先创建一个项目列表,我将循环以从API响应中提取信息。然后我创建了一个数据框,用于存储有关没有错误的项目的信息。
l= ["a","b","c","d"]
def extract_info_from_one_response(response, idx):
try:
response = response.json()
d = {
### some codes ##
}
## ERROR MANAGEMENT
except KeyError,e:
print idx, l[idx], str(e)
return {}
except IndexError,e:
print idx, l[idx], str(e)
return {}
dat = pd.DataFrame([extract_info_from_one_response(response, idx) for idx, response in enumerate(responses)], index=l)
当出现错误时,Python打印出[1]有问题项的索引,[2]项目名称和[3]发生错误的详细信息。如何保存/捕获这三个输出,将它们保存到对象中或使用这3个信息创建数据帧?
答案 0 :(得分:0)
我不确定你在问什么,但如果你想保存打印的内容:
key_err = []
idx_err = []
def extract_info_from_one_response(response, idx):
try:
# your code here
except KeyError, e:
key_err.append((idx, l[idx], '{}'.format(e),))
return {}
except IndexError, e:
idx_err.append((idx, l[idx], '{}'.format(e),))
return {}
# your normal code here
# you need to return something here
dat = pd.DataFrame([extract_info_from_one_response(response, idx) for idx, response in enumerate(responses)], index=l)
print(key_err)
print(idx_err)
答案 1 :(得分:0)
您是否在询问如何追踪错误?
如果是这样,追溯模块会有这样的帮助:
In [1]: import traceback
In [2]: try:
...: a = []
...: a[2] = 1
...: except Exception:
...: y = traceback.format_exc()
...:
In [4]: print y
Traceback (most recent call last):
File "<ipython-input-2-ac34fe2721d3>", line 3, in <module>
a[2] = 1
IndexError: list assignment index out of range