The subprocess module enables you to start new applications from your Python program. How cool is that?
Complete Python Bootcamp: Go from zero to hero in Python 3
Start a process in Python:
You can start a process in Python using the Popen function call. The program below starts the unix program ‘cat’ and the second parameter is the argument. This is equivalent to ‘cat test.py’. You can start any program with any parameter.
The process.communicate() call reads input and output from the process. stdout is the process output. stderr will be written only if an error occurs. If you want to wait for the program to finish you can call Popen.wait().
Subprocess has a method call() which can be used to start a program. The parameter is a list of which the first argument must be the program name. The full definition is:
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
In the example below the full command would be “ls -l”
Save process output (stdout)
We can get the output of a program and store it in a string directly using check_output. The method is defined as:
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)