Python错误处理重试代码

时间:2018-05-16 14:49:12

标签: python python-3.x error-handling

我正在尝试构建一个定义,对我的定义进行错误检查。构造此代码以进行错误处理的正确方法是什么?

我希望脚本运行指定的定义,如果失败,重试多次,如果超时则终止它。

import time

def open_file():
    open('testfile.py')

def run_def(definition):
    for i in range(0, 4):
        try:
            definition
            str_error = None
        except Exception as str_error:
            pass
            if str_error:
                time.sleep(1)
                print(str_error)
            else:
                break
                print('kill script')

run_def(open_file())

当我尝试将定义传递给错误检查定义时,我收到错误。但是如果我不将错误检查器放入单独的定义中,脚本就可以工作。

FileNotFoundError: [Errno 2] No such file or directory: 'testfile.py'

1 个答案:

答案 0 :(得分:1)

我不确定你想要做什么,但如果你想捕捉异常,你的通话功能应放在你的try / except区块内。

像这样:

import time

def open_file():
    open('testfile.py')

def run_def(definition):
    for i in range(0, 4):
        try:
            definition()
        except Exception as str_error:
            if str_error:
                time.sleep(1)
                print(str_error)
            else:
                break
                print('kill script')

run_def(open_file)

您不需要在except之后传递。

您之前不需要初始化str_error变量。 (除非你之前使用它...)