Python Subprocess – How to Execute a Program or Call a System Command

commandpythonshellsubprocessterminal

How do I call an external command within Python as if I had typed it in a shell or command prompt?

Best Answer

Use subprocess.run:

import subprocess

subprocess.run(["ls", "-l"]) 

Another common way is os.system but you shouldn't use it because it is unsafe if any parts of the command come from outside your program or can contain spaces or other special characters, also subprocess.run is generally 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.

On Python 3.4 and earlier, use subprocess.call instead of .run:

subprocess.call(["ls", "-l"])
Related Question