按顺序运行功能的最佳实践是什么?
我有4个功能,如果前一个功能失败,请不要运行以下功能。在每个函数中,当发生异常时,我都设置global error
和error = 1
。然后在主要情况下,我只使用if语句检查error
的值。我认为应该有一个更好的方法。
def main():
engine = conn_engine()
if error == 0:
process_sql()
if error == 0:
append_new_rows_to_prod()
if error == 0:
send_email_log()
最佳答案
规范的方法是在函数内引发异常。例如:
def process_sql():
# Do stuff
if stuff_failed:
raise ProcessSQLException("Error while processing SQL")
def append_new_rows_to_prod():
# Do other stuff
if other_stuff_failed:
raise AppendRowsException("Error while appending rows")
def main():
engine = conn_engine()
try:
process_sql()
append_new_rows_to_prod()
send_email_log()
except ProcessSQLException, AppendRowsException as e:
# Handle exception, or gracefully exit
关于python - Python按顺序运行函数;如果失败,请停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64057331/