You're looking for the subprocess
module, which is part the standard library.
The subprocess
module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
In Unix systems, this means subprocess
can spawn new Unix processes, execute their results, and fetch you back their output. Since a bash script is executed as a Unix process, you can quite simply tell the system to run the bash script directly.
A simple example:
import subprocess
ls_output = subprocess.check_output(['ls']) # returns result of `ls`
You can easily run a bash script by stringing arguments together. Here is a nice example of how to use subprocess
.
All tasks in subprocess
make use of subprocess.Popen()
command, so it's worth understanding how that works. The Python docs offer this example of calling a bash script:
>>> import shlex, subprocess
>>> command_line = raw_input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print args
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
Note the only important part is passing a list of arguments to Popen()
.