以下不起作用。我有一个程序连接到一个网页,但有时由于一些问题,它无法连接我希望程序完全重新启动错误全部由它自己。想象一下main函数调用程序,我该如何编写这样的代码?
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()
答案 0 :(得分:1)
对于这样的事情(连接到网页),通常最好根据时间而不是尝试连接的次数来设置上限。因此,请改用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
可选:每次尝试失败后,我都会暂停100毫秒。这有助于建立连接。
然后将整个事情包装在一个函数中,以后可以用于其他项目:
# retry.py
import time
def retry(f, seconds, pause = 0):
start = time.time()
stop = start + seconds
attempts = 0
result = 'failed'
while True:
if time.time()<stop:
try:
f()
except Exception as e:
attempts += 1
print e
time.sleep(pause)
print 'Restarting!'
continue
else:
result = 'succeeded'
print '%s after %i attempts.' % (result, attempts)
break
现在就这样做:
import numpy as np
from retry import retry
def main():
np.load('file.csv')
retry(main, 5, 0.1)
测试程序:
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.
答案 1 :(得分:1)
你可以在这里使用递归函数自动重启你的代码。使用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
希望这有助于:)