Asked : Nov 17
Viewed : 22 times
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?
Nov 17
Use the subprocess
module in the standard library:
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...).
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 thesubprocess
documentation for some helpful recipes.
On Python 3.4 and earlier, use subprocess.call
instead of .run
:
subprocess.call(["ls", "-l"])
answered Jan 18
I'd recommend using the subprocess module instead of os.system because it does shell escaping for you and is therefore much safer.
subprocess.call(['ping', 'localhost'])
answered Jan 18
Use subprocess.call:
from subprocess import call
# Using list
call(["echo", "Hello", "world"])
# Single string argument varies across platforms so better split it
call("echo Hello world".split(" "))
answered Jan 18
However, if the command generates any output, it is sent to the interpreter standard output stream. Using this command is not recommended. In the following code, we will try to know the version of git using the system command git --version
.
import os
cmd = "git --version"
returned_value = os.system(cmd) # returns the exit code in unix
print('returned value:', returned_value)
answered Jan 18
In the previous section, we saw that os.system()
function works fine. But it’s not recommended way to execute shell commands. We will use the Python subprocess module to execute system commands.
We can run shell commands by using subprocess.call()
functions. See the following code which is equivalent to the previous code.
import subprocess
cmd = "git --version"
returned_value = subprocess.call(cmd, shell=True) # returns the exit code in unix
print('returned value:', returned_value)
answered Jan 18