21

I have 2 python scripts a.py and b.py and I want to write a bash script that will load a.py and not run b.py until a.py is done doing it's thing. simplistically

#!/usr/bin/env bash
python a.py
python b.py

but this is naive, a check to see if a.py is done... how do I do that?

StudentOfScience
  • 809
  • 3
  • 11
  • 35
  • 3
    That's the natural behavior, synchronous execution. If you wanted it otherwise (to run a in the background and immediately start b) you should append an ampersand & to the command, e.g. `python a.py&`. – Morten Jensen Dec 03 '12 at 22:05

2 Answers2

47

This by default will already run one after the other.


To check that python a.py completed successfully as a required condition for running python b.py, you can do:

#!/usr/bin/env bash
python a.py && python b.py

Conversely, attempt to run python a.py, and ONLY run 'python b.py' if python a.py did not terminate successfully:

#!/usr/bin/env bash
python a.py || python b.py

To run them at the same time as background processes:

#!/usr/bin/env bash
python a.py &
python b.py &

(Responding to comment) - You can chain this for several commands in a row, for example:

python a.py && python b.py && python c.py && python d.py 
sampson-chen
  • 45,805
  • 12
  • 84
  • 81
  • 1
    can this be for more than two? if I also had c.py,`code` python a.py && python b.py && python c.py `code` or have to do another line for c.py separately? first `code` python a.py && python b.py`code` then `code`python b.py && python c.py`code` – StudentOfScience Dec 03 '12 at 22:06
  • Using the && it gives an error ./bash.sh: line 47: b.py: command not found but it runs b.py if I have it as python b.py fine :( – StudentOfScience Dec 03 '12 at 22:14
  • @StudentOfScience that's if you were doing `python a.py && b.py` - can you show us what your script looks like and how you are invoking it? – sampson-chen Dec 03 '12 at 22:19
  • Ok, dont mean to hijack the thread but its quite related. What if a.py logs something using the print command and based on the results, I would want to call b.py? I guess it would be best to check within a.py in order to call b.py? The code being `x = ser.readline() print "got '" + x + "'"` so then if AT+OK is received then call b.py. – marciokoko May 16 '17 at 21:13
  • what if I have for scripts: `parent.py`, `child1.py`,`child2.py`, `reunion.py`, I want `parent.py` to run first, then run `child1.py` and `child2.py` simultaneously, finally run `reunion.py` if both `child1.py` and `child2.py` are succeeded? – Jia Gao Feb 23 '19 at 20:23
0
prompt_err() {

echo -e "\E[31m[ERROR]\E[m"

}

prompt_ok() {

echo -e "\E[32m[OK]\E[m"

}

status() {

if [ $1 -eq 0 ]; then

prompt_ok

else prompt_err

exit -1

fi

}

a.py

status

b.py

You can use the check code above.

If 'a.py' is done only then it will process 'b.py', otherwise it will exit with an 'Error'.

Mansab Uppal
  • 653
  • 5
  • 4