python - Python错误处理重试代码

标签 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'

最佳答案

我不确定您要做什么,但是如果您想捕获异常,则应将调用函数放在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变量。 (除非您之前使用过...)

关于python - Python错误处理重试代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50374010/

相关文章:

python - 如何在不使用列表的情况下转换字符串中的数字?

python - 使用 python 3 中的 matplotlib 在堆叠条形图中堆叠多列

swift - CLGeocoder()。geocodeAddressString错误代码

shell - 如果收到 SIGINT 或 SIGTERM,是否需要执行 trap EXIT?

Python:计算两列内值的组合并找到每个组合的最大频率

python - 当第一个子字符串后有空格时,在 Python 中查找两个子字符串之间的字符串

python - Python 中的石头、布、剪刀(大于和小于)

python - 在 Google Colab 环境中运行云 TPU 分析器

python - Django注释返回多个

apache-spark - 当我尝试将文件查找到HDFS中时出现NullPointerException Spark