Computer Science Atlas
Snippets

Python 3: Execute a System Command Using subprocess.run()

Part 1 of a Series: subprocess.run()
July 12, 2021
 
Articles in Series: subprocess.run()
  1. Current Article
    Python 3: Execute a System Command Using subprocess.run()
  2. Python 3: Get and Check Exit Status Code (Return Code) from subprocess.run()
  3. Python 3: Get Standard Output and Standard Error from subprocess.run()
  4. Python 3: Standard Input with subprocess.run()
  5. Python 3: Using Shell Syntax with subprocess.run()
  6. Python 3: Specify Environment Variables in subprocess.run()
Table of Contents

Python 3.5 or Higher Required

subprocess.run() allows you to run other programs and system commands from a Python script. It is built into Python versions 3.5 and up.

Run / Execute a System Command

To run the system command ls -alF /etc from a Python script, we can write:

from subprocess import run

run( [ 'ls', '-alF', '/etc' ] )
1
2
3
from subprocess import run

run( [ 'ls', '-alF', '/etc' ] )

Note that we break up the command into a list of strings where:

  1. the name of the command ls is one string, and
  2. each argument (-alF and /etc) is each represented by a separate string.

In other words, run() accepts commands as a list of strings with the following format:

[ command_name, arg1, arg2, arg3, ... ]

We can run ls without any arguments like this:

from subprocess import run

run( [ 'ls' ] )
1
2
3
from subprocess import run

run( [ 'ls' ] )

And we can run echo "Hello, world!" like this:

from subprocess import run

run( [ 'echo', 'Hello, world!' ] )
1
2
3
from subprocess import run

run( [ 'echo', 'Hello, world!' ] )

The command's standard output (stdout) and standard error (stderr) are directed by default to our Python program's stdout and stderr. That means if we're running our Python program in a terminal window, the output of the subprocess will show up in the window in real time.

Similarly, our Python program's standard input (stdin) is passed through to the command, so if the command we're calling shows an input prompt and waits for user input, our Python program calling that command will do the same.

References