如果函数中断,如何从函数内部返回良好的数据?

2024-04-26 10:35:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我从一个web api(使用python)收集数据,并使用一个循环遍历数千个对api的调用。功能运行正常,但我的电脑进入睡眠状态,互联网连接中断。调用api时,我将数据存储为字典列表。我的问题是:当函数失败时,由于我的列表在函数中,我甚至无法获得它在失败之前成功进行的数百次调用。我如何添加错误处理或其他方法,以便在某个点(比如500次调用后)失败时,仍然可以获得499条数据

如果我在没有将代码放入函数的情况下运行代码,我的列表在代码崩溃之前仍然是可行的,但我觉得将代码放入函数“更正确”

#this is how the function is set up in pseudo-code:
def api_call(x):
    my_info = []
    for i in x:
        dictionary = {}
        url=f'http://www.api.com/{x}'
        dictionary['data'] = json['data']
        my_info.append(dictionary)
    return my_info

another_variable = api_call(x)

Tags: 数据函数代码in功能infoapiweb
1条回答
网友
1楼 · 发布于 2024-04-26 10:35:38

只需将其包装在try/except/finally块中。finally总是在离开try语句之前执行。finally块所做的解释是here

def api_call(x):
    my_info = []
    try:
        for i in x:
            dictionary = {}
            url=f'http://www.api.com/{x}'
            dictionary['data'] = json['data']
            my_info.append(dictionary)
    except Exception as e:
        print('Oopsie')  # Can log the error here if you need to 
    finally:
        return my_info

another_variable = api_call(x)

相关问题 更多 >