如何在python代码出现错误后自动重新启动它?
下面的方法不起作用。我有一个程序可以连接到一个网页,但有时由于一些问题,它无法连接,我希望程序在出错后完全重新启动。想象一下主函数调用程序,我如何编写这样的代码如何在python代码出现错误后自动重新启动它?,python,Python,下面的方法不起作用。我有一个程序可以连接到一个网页,但有时由于一些问题,它无法连接,我希望程序在出错后完全重新启动。想象一下主函数调用程序,我如何编写这样的代码 import numpy as np def main(): np.load('File.csv') for i in range(1, 10): try: main() except Exception as e: print e print 'Restart
import numpy as np
def main():
np.load('File.csv')
for i in range(1, 10):
try:
main()
except Exception as e:
print e
print 'Restarting!'
main()
要在python内部执行此操作,请相应地使用
try/except
:
import numpy as np
def main():
np.load('File.csv')
for i in range(1, 10):
try:
main()
except Exception as e:
print e
print 'Restarting!'
continue
else:
break
对于简单的指令,这是可行的,但如果代码变得更复杂,将整个main()
函数放入try/except
块会隐藏异常,并使程序难以调试。因此,我建议在python之外处理重启,例如在bash脚本中 对于这种情况(连接到网页),通常最好根据时间设置上限,而不是根据尝试连接的次数。因此,请改用while
循环:
import numpy as np
import time
def main():
np.load('file.csv')
start = time.time()
stop = start + 5
attempts = 0
result = 'failed'
while True:
if time.time()<stop:
try:
main()
except Exception as e:
attempts += 1
print e
time.sleep(0.1) # optional
print 'Restarting!'
continue
else:
result = 'succeeded'
print 'Connection %s after %i attempts.' % (result, attempts)
break
测试程序:
class RetryTest():
def __init__(self, succeed_on = 0, excp = Exception()):
self.succeed_on = succeed_on
self.attempts = 0
self.excp = excp
def __call__(self):
self.attempts += 1
if self.succeed_on == self.attempts:
self.attempts = 0
else:
raise self.excp
retry_test1 = RetryTest(3)
retry(retry_test1, 5, 0.1)
# succeeded after 3 attempts.
retry_test2 = RetryTest()
retry(retry_test2, 5, 0.1)
# failed after 50 attempts.
您可以在这里很好地使用递归函数来自动重新启动代码。使用setrecursionlimit()定义尝试次数,如下所示:
import numpy as np
import sys
sys.setrecursionlimit(10) # set recursion depth limit
def main():
try:
a = np.load('file.csv')
if a:
return a
except Exception as e:
return main()
result = main()
print result
希望这能有所帮助:)@auryndb它之前实际上有点坏了;现在修好了。
class RetryTest():
def __init__(self, succeed_on = 0, excp = Exception()):
self.succeed_on = succeed_on
self.attempts = 0
self.excp = excp
def __call__(self):
self.attempts += 1
if self.succeed_on == self.attempts:
self.attempts = 0
else:
raise self.excp
retry_test1 = RetryTest(3)
retry(retry_test1, 5, 0.1)
# succeeded after 3 attempts.
retry_test2 = RetryTest()
retry(retry_test2, 5, 0.1)
# failed after 50 attempts.
import numpy as np
import sys
sys.setrecursionlimit(10) # set recursion depth limit
def main():
try:
a = np.load('file.csv')
if a:
return a
except Exception as e:
return main()
result = main()
print result