#python #list #loops #exception
#python #Список #циклы #исключение
Вопрос:
В моем скрипте у меня следующая структура:
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.
Мне нужно, чтобы скрипт продолжался по другим идентификаторам в списке.
Комментарии:
1. Вместо обработки исключений в вашем
get_data
, вы бы сделалиtry-except
блок в своем цикле вокруг вашего вызоваget_data
, иcontinue
если возникает исключение.
Ответ №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')