how to execute a bash command in a python script
@milne's answer works, but subprocess.call()
gives you little feedback.
I prefer to use subprocess.check_output()
so you can analyse what was printed to stdout:
import subprocess
res = subprocess.check_output(["sudo", "apt", "update"])
for line in res.splitlines():
# process the output line by line
check_output
throws an error on on-zero exit of the invoked command
Please note that this doesn't invoke bash
or another shell if you don't specify the shell
keyword argument to the function (the same is true for subprocess.call()
, and you shouldn't if not necessary as it imposes a security hazard), it directly invokes the command.
If you find yourself doing a lot of (different) command invocations from Python, you might want to look at plumbum. With that you can do the (IMO) more readable:
from plumbum.cmd import sudo, apt, echo, cut
res = sudo[apt["update"]]()
chain = echo["hello"] | cut["-c", "2-"]
chain()
It is possible you use the bash as a program, with the parameter -c for execute the commands:
Example:
bashCommand = "sudo apt update"
output = subprocess.check_output(['bash','-c', bashCommand])
The subprocess module is designed to do this:
import subprocess
subprocess.call(["sudo", "apt", "update"])
If you would like the script to terminate if the command fails, you might consider using check_call()
instead of parsing the return code yourself:
subprocess.check_call(["sudo", "apt", "update"])