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

2024-09-28 22:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用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次吗?也就是说可以配置这个号码吗?在


Tags: 脚本bashbinstderrstdoutscriptprocshell
3条回答
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

用个装饰工怎么样?看起来很清楚。 你可以在这里阅读https://wiki.python.org/moin/PythonDecoratorLibrary。(重试装饰器)

可能是这样:

maxRetries = 6
retries = 0

while (retries < maxRetries):
    doSomething ()
    if errorCondition:
        retries += 1
        continue
    break

相关问题 更多 >