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?

python shell terminal subprocess command 

Nov 17

5 Answers

Use the subprocess module in the standard library:

import subprocess["ls", "-l"])

The advantage of 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 instead of .run:["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.['ping', 'localhost'])

answered Jan 18


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

Python Function

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 functions. See the following code which is equivalent to the previous code.

import subprocess

cmd = "git --version"

returned_value =, shell=True)  # returns the exit code in unix
print('returned value:', returned_value)


answered Jan 18

Login and Submit Your Answer
Browse other questions tagged  python  shell  terminal  subprocess  command or ask your own question.