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.
To run the system command ls -alF /etc from a Python script, we can write:
1 2 3 | from subprocess import run run( [ 'ls', '-alF', '/etc' ] ) |
Note that we break up the command into a list of strings where:
ls is one string, and-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:
1 2 3 | from subprocess import run run( [ 'ls' ] ) |
And we can run echo "Hello, world!" like this:
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.