我试图在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