I am working on a project in which I need to execute shell script using Python. And so far everything is looking good.
Below is my Python script which will execute a simple hello world shell script.
MAX_TRIES = 2
jsonStr = '{"script":"#!/bin/bash \\n echoo Hello world 1 "}'
j = json.loads(jsonStr)
shell_script = j['script']
steps = ['step1', 'step2', 'step3']
for step in steps:
print "start"
print step
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..."
sleep(0.05) # delay for 50 ms
else:
print "end" # Shell script ran fine.
break
In my above script, I am retrying two times if my above shell script gets failed for whatever reason and it is working fine.
Now the question I have is, in my above script, I have a wrong shell script which will get failed. And I have a for loop which will iterate steps list one by one and execute the shell script.
And currently it is getting printed out like this for each steps which is not what I want -
start
step1
Shell script gave some error...
Shell script gave some error...
start
step2
Shell script gave some error...
Shell script gave some error...
start
step3
Shell script gave some error...
Shell script gave some error...
If the shell script failed for the first step, then I don't want to go for step2 but I want to retry two times for each step. Suppose if the shell script execution failed for step1, then I want to retry two times for step1 and if it gets failed twice, then I won't go for step2 but if it passes, then only I will go for step2.
How do I break my outer loops in such a way so that I can accomplish this?
UPDATE:-
for step in steps:
print "start"
print step
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
else:
break