How do I call an external command within Python as if I had typed it in a shell or command prompt?
Python Subprocess – How to Execute a Program or Call a System Command
commandpythonshellsubprocessterminal
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
: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, alsosubprocess.run
is generally more flexible (you can get thestdout
,stderr
, the "real" status code, better error handling, etc.). Even the documentation foros.system
recommends usingsubprocess
instead.On Python 3.4 and earlier, use
subprocess.call
instead of.run
: