How to Call an external command with Python?



Here we explain how to call an external command like you will do it in the shell, but using Python.

For python 2 and 3 the subprocess module is recommended over the alternative os.system() Remember that using subprocess from a web server could be dangerous since command injection could be possible.

Python 3: Using the subprocess module

The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. You can use Popen for more advance usages.

import subprocess
result = subprocess.run(["ps", "ax"])

Run will return a CompletedProcess instance. The returned object has:

  • stdout: output printed to standard output
  • stderr: errors printd in the standard error
  • return_code: program return code
  • args: arguments used to call the command

For example, if you need to check for errors use result.stderr.

When using run you have some usefull parameters like shell and verify:

  • shell: When True the specified command will be executed through the shell.
  • verify: When True the process exits with a non-zero exit code.

Python 2: Using the subprocess module

With python 2 we have the call method instead of run and it accepts a list or string. When using a list you can split the command and their arguments.

import subprocess
subprocess.call(["ps", "ax"])

Call cupport the following arguments:

  • stdin: standard input to communicate with the process
  • stdout: output printed to standard output
  • stderr:errors printd in the standard error
  • shell: defaults to False

Remeber that Using shell=True can be a security hazard


Check here for full subprocess module official documentation: * Python 2 subprocess documentation * Python 3 subprocess documentation