我正在尝试在Python代码中执行Shell脚本。到目前为止,一切都看起来不错。
下面是我的Python脚本,它将执行一个shell脚本。现在来看一个示例,这是一个简单的Hello World 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次吗?意味着也可以配置该号码吗?
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句