【问题标题】:Python continue looping over a list even when a connection error occurs即使发生连接错误,Python 也会继续循环遍历列表
【发布时间】:2021-03-20 20:15:07
【问题描述】:

我的脚本中有以下结构:

id_list = [1, 2, 3]
for id in id_list:
    data = get_data(id)
    meta = get_metadata(id)
    # If there is a response, continue:
    if((data.json()) and (data.json())['job_status']=='SUCCESS'):
        # Do stuff
    else:
        print('Id is not found')

这里是get_data() 脚本:

def get_data(form_id):
    survey_found = False
    try:
        print("------- Getting data from Source. Please wait. -------\n")
        print("------- Getting data from Source. Please wait. -------\n", file=logfile)
        response.raise_for_status()
        print(response.content)
        survey_found = True
        return response
    except (RuntimeError, TypeError, NameError, snowCtx.connection.errors.Error, requests.exceptions.HTTPError) as e:
        print("******* Error from Source (GETTING DATA): *******\n"+ str(e)+" on form id: "+str(form_id))
        print("******* Error from Source (GETTING DATA): *******\n"+ str(e)+ str(e)+" on form id: "+str(form_id), file=logfile)
        survey_found = False
        return survey_found

我不关心get_meta(),因为条件是get_data()

问题是如果第一个id 不可用,代码将停止执​​行,因为except 部分将引发http 错误。

我需要脚本继续处理列表中的其他 ID。

【问题讨论】:

标签: python list loops exception


【解决方案1】:
id_list = [1, 2, 3]
for id in id_list:
    data = get_data(id)
    if isinstance(data, bool) and not data:
        print(f"skipping {id}...")
        continue
    meta = get_metadata(id)
    if((data.json()) and (data.json())['job_status']=='SUCCESS'):
        # Do stuff
    else:
        print('Id is not found')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    相关资源
    最近更新 更多