How do you 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:
subprocess
import subprocess subprocess.run(["ls", "-l"])
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...).
subprocess.run
os.system
stdout
stderr
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
.run
subprocess.call(["ls", "-l"])
2.1m questions
2.1m answers
60 comments
57.0k users