繁体   English   中英

在python脚本中执行命令

[英]commands execution in python script

我有一个带有要执行的命令的python脚本,例如:

sample_command_that_may_fail()

假设上述命令由于网络问题而失败,并且仅在执行该命令2-3次后才成功。

我在python中有很多内置的函数可以重试它,或者有可用的链接或提示吗?我是python的新手,因为对此的任何链接都对我有帮助。

您可以考虑重试模块。

例:

import random
from retrying import retry

@retry
def do_something_unreliable():
    if random.randint(0, 10) > 1:
        raise IOError("Broken sauce, everything is hosed!!!111one")
    else:
        return "Awesome sauce!"

print do_something_unreliable()

由于您没有提供任何细节,因此很难做到更好,更具体,但是通常您只能使用for循环。 一个例子可能看起来像:

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')

这将尝试my_command() 3次。 它对my_command()的行为做出了一些假设:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM