我有一个每隔几秒查询一次 API 的程序。每个响应都会触发一些功能,这些功能本身会调用网站等——我不想盲目相信这些调用会成功。例如,如果我在 foo()
中捕获异常,或者甚至在 foo()
调用的函数中捕获异常,是否有可能在 except block 中完全重新启动程序?本质上,我想在其子函数之一出现异常时调用 queryRepeatedly()
,而不将之前的调用保留在堆栈中。
当然,我可以返回标记值并以另一种方式解决这个问题,但程序的结构使得上述方法看起来更加简单和清晰。
# Sample "main" function that I want to call
def queryRepeatedly():
while True:
foo()
bar()
baz()
time.sleep(15)
def foo():
# do something
try:
foo2() # makes a urllib2 call that I don't trust
except:
#restart queryRepeatedly
queryRepeatedly()
最佳答案
要重新启动任何东西,只需在try
之外使用while
循环。例如:
def foo():
while True:
try:
foo2()
except:
pass
else:
break
如果您想将异常向上传递到链中,只需在外部函数而不是内部函数中执行此操作:
def queryRepeatedly():
while True:
while True:
try:
foo()
bar()
baz()
except:
pass
else:
break
time.sleep(15)
def foo():
foo2()
所有这些缩进有点难以阅读,但重构它很容易:
def queryAttempt()
foo()
bar()
baz()
def queryOnce():
while True:
try:
queryAttempt()
except:
pass
else:
break
def queryRepeatedly():
while True:
queryOnce()
time.sleep(15)
但是如果你仔细想想,你也可以把两个while
循环合并为一个。 continue
的使用可能有点困惑,但看看你是否更喜欢它:
def queryRepeatedly():
while True:
try:
foo()
bar()
baz()
except:
continue
time.sleep(15)
关于python - 异常后重启程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17533104/