[英]commands execution in python script
I have a python script with a command to be executed like for example: 我有一个带有要执行的命令的python脚本,例如:
sample_command_that_may_fail()
Assuming that the above command fails due to network issues and if it succeeds only after 2-3 times executing the command. 假设上述命令由于网络问题而失败,并且仅在执行该命令2-3次后才成功。
is there any built in function in python for retrying it or any links or hints available?I am very much novice in python, as any links to this would be of help to me. 我在python中有很多内置的函数可以重试它,或者有可用的链接或提示吗?我是python的新手,因为对此的任何链接都对我有帮助。
Since you didn't give any specifics, it's hard to be more, well, specific, but typically you can just use a for
loop. 由于您没有提供任何细节,因此很难做到更好,更具体,但是通常您只能使用
for
循环。 An example might look like: 一个例子可能看起来像:
out = None
# Try 3 times
for i in range(3):
try:
out = my_command()
# Catch this specific error, and do nothing (maybe you can also sleep for a few seconds here)
except NetworkError:
pass
# my_command() didn't raise an error, break out of the loop
else:
break
# If it failed 3 times, out will still be None
if out is None:
raise Exception('my_command() failed')
This tries my_command()
3 times. 这将尝试
my_command()
3次。 It makes some assumptions about the behaviour of my_command()
: 它对
my_command()
的行为做出了一些假设:
NetworkError
on a network error; NetworkError
; take care to avoid pokemon exceptions . None
on success. None
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.