Equivalent of Bash Backticks in Python
The most flexible way is to use the subprocess
module:
import subprocess
out = subprocess.run(["cat", "/tmp/baz"], capture_output=True)
print("program output:", out)
capture_output
was introduced in Python 3.7, for older versions the special function check_output()
can be used instead:
out = subprocess.check_output(["cat", "/tmp/baz"])
You can also manually construct a subprocess object if you need fine grained control:
proc = subprocess.Popen(["cat", "/tmp/baz"], stdout=subprocess.PIPE)
(out, err) = proc.communicate()
All these functions support keyword parameters to customize how exactly the subprocess is executed. You can for example use shell=True
to execute the program through the shell, if you need things like file name expansions of *
, but that comes with limitations.
output = os.popen('cat /tmp/baz').read()