Computer Science Atlas
Code Review

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

Part 1 of a Series
July 12, 2021
 

Articles in Series

  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()

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:

Copy
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:

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

We can run ls without any arguments like this:

Copy
from subprocess import run

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

run( [ 'ls' ] )

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

Copy
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

Articles in Series

  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()