在python中引发异常时重新运行逻辑

时间:2014-07-20 19:02:43

标签: python exception-handling

我正在尝试在python

中发生异常时实现重新运行逻辑

--------- --------- rerun.py

from test import TEST
my_test=TEST(parser.parse_args())
rerun=0
try:
    my_test.main()
except Exception as e:
    print "caught here"
    rerun=rerun+1
    if rerun<3:
        my_test.main()

main()调用其他方法,并在其中一种方法中引发异常。

EX: ---- --- test.py

   def some_method(self):
        raise Exception("testing")

   def main(self):

        self.some_method()

当第一次引发异常时,重新运行但在下一次运行中它不会将异常返回给rerun.py。而是通过刺激引发的异常退出

由于

1 个答案:

答案 0 :(得分:0)

您可以将此通用重试功能设为:

def run_with_retries(func, num_retries, exception_types=(Exception,)):
    for i in range(num_retries):
        try:
            # call the function
            return func()
        except exception_types, e:
            # failed on the known exception
            if i == num_retries - 1:
                # this was the last attempt. reraise
                raise
            # retry ...
    assert 0  # should not reach this point

在您的情况下,请将其命名为:

run_with_retries(my_test.main, 3)