简体   繁体   English

在python脚本中执行命令

[英]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的新手,因为对此的任何链接都对我有帮助。

You may consider retrying module. 您可以考虑重试模块。

Example: 例:

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

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()的行为做出了一些假设:

  • It raises a NetworkError on a network error; 它在网络错误时引发NetworkError take care to avoid pokemon exceptions . 注意避免宠物小精灵的异常
  • It returns something other than None on success. 如果成功,则返回None

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

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