Python 如果shell脚本执行失败,如何实现重试机制?

Python 如果shell脚本执行失败,如何实现重试机制?,python,bash,shell,subprocess,Python,Bash,Shell,Subprocess,我正在尝试用Python代码执行shell脚本。到目前为止,一切看起来都很好 下面是我的Python脚本,它将执行一个shell脚本。现在,作为一个示例,这里是一个简单的helloworld shell脚本 jsonStr = '{"script":"#!/bin/bash\\necho Hello world 1\\n"}' j = json.loads(jsonStr) shell_script = j['script'] print "start" proc = subprocess.

我正在尝试用Python代码执行shell脚本。到目前为止,一切看起来都很好

下面是我的Python脚本,它将执行一个shell脚本。现在,作为一个示例,这里是一个简单的helloworld shell脚本

jsonStr = '{"script":"#!/bin/bash\\necho Hello world 1\\n"}'
j = json.loads(jsonStr)

shell_script = j['script']

print "start"
proc = subprocess.Popen(shell_script, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = proc.communicate()
if stderr:
   print "Shell script gave some error"
   print stderr
else:
   print stdout
   print "end" # Shell script ran fine.
现在我要寻找的是,假设无论出于什么原因,每当我从Python代码执行shell脚本时,无论出于什么原因它都失败了。那就意味着
stderr
不会为空。现在我想再次尝试执行shell脚本,比如说在睡眠几毫秒后


意思是,如果shell脚本执行失败,是否有可能实现重试机制?我可以重试5次或6次吗?也就是说,是否可以配置此号码?

类似的内容可能是:

maxRetries = 6
retries = 0

while (retries < maxRetries):
    doSomething ()
    if errorCondition:
        retries += 1
        continue
    break
maxRetries=6
重试次数=0
而(重试次数<最大重试次数):
剂量测定法()
如果出现错误情况:
重试次数+=1
持续
打破

使用装饰器怎么样?这似乎是一条非常清晰的道路。
你可以在这里读到他们。(重试装饰程序)

谢谢您的建议。但是如何将其与当前代码集成?在我的python脚本中,我正在执行一个shell脚本,如果由于任何原因失败,我想重试。如果您的代码不是cargo cult,您应该能够轻松地集成它。
doSomething
是您的子流程调用,
errorCondition
是您问题中指定的错误条件。
用于TRY in xrange
?这个语法正确吗?我希望出现
SyntaxError:invalid syntax
。对于需要描述性变量名且存在此问题的情况,
try
是“try”的同义词;)@卡尔克内切特尔——是的!:-)事实上,如果我是为自己写这篇文章的话,我会使用
\uu
作为迭代器变量,因为这通常被用作一次性/未使用的名称,但我认为如果OP对此不熟悉的话,这可能会使事情更加混乱。显然有些人不喜欢
\u
作为迭代器变量,因为有些替代的repl(例如,IronPython提供的IIRC)赋予它一个特殊的含义(它存储前面表达式的值)。但在我看来,这个反对意见相当愚蠢。:)
from time import sleep
MAX_TRIES = 6

# ... your other code ...

for i in xrange(MAX_TRIES):
    proc = subprocess.Popen(shell_script, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (stdout, stderr) = proc.communicate()
    if stderr:
       print "Shell script gave some error..."
       print stderr
       sleep(0.05) # delay for 50 ms
    else:
       print stdout
       print "end" # Shell script ran fine.
       break