How do I call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?
Use the subprocess module in the standard library.
import subprocess import sys command = subprocess.run(['ls', '-l'], capture_output=True) sys.stdout.buffer.write(command.stdout) sys.stderr.buffer.write(command.stderr) sys.exit(command.returncode)
The advantage of subprocess.run
over os.system
is that it is more flexible (you can get the stdout
, stderr
, the "real" status code, better error handling, etc...).
Even the documentation for os.system
recommends using subprocess
instead:
The subprocess
module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess
documentation for some helpful recipes.
On Python 3.4 and earlier, use subprocess.call instead of .run:
subprocess.call(["ls", "-l"])