python脚本中的命令执行

python脚本中的命令执行,python,Python,我有一个python脚本,其中包含要执行的命令,例如: sample_command_that_may_fail() 假设上述命令由于网络问题而失败,并且仅在执行该命令2-3次后才成功 在Python中是否有任何内置函数用于重试它或任何可用的链接或提示?我在Python中非常新手,因为任何链接对我都有帮助。 你可以考虑模块。 例如: import random from retrying import retry @retry def do_something_unreliable():

我有一个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()

你可以考虑模块。 例如:

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_命令()
3次。它对
my_command()
的行为做了一些假设:

  • 它会在网络错误上引发
    NetworkError
    ;注意避免发生意外
  • 成功时,它返回的不是
    None

    • 由于您没有给出任何细节,因此很难更具体,但通常您可以使用
      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_命令()
      3次。它对
      my_command()
      的行为做了一些假设:

      • 它会在网络错误上引发
        NetworkError
        ;注意避免发生意外
      • 成功时,它返回的不是
        None