python logo

Tag: subprocess

python subprocess

The subprocess module enables you to start new applications from your Python program. How cool is that?

Related Course:
Python Programming Bootcamp: Go from zero to hero

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’.  You can start any program with any parameter.

#!/usr/bin/env python

from subprocess import Popen, PIPE

process = Popen(['cat', ''], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
print stdout

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

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:, *, stdin=None, stdout=None, stderr=None, shell=False)
# Run the command described by args.
# Wait for command to complete, then return the returncode attribute.

In the example below the full command would be “ls -l”

#!/usr/bin/env python

import subprocess["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)
# Run command with arguments and return its output as a byte string.

Example usage:

#!/usr/bin/env python
import subprocess

s = subprocess.check_output(["echo", "Hello World!"])
print("s = " + s)

If you are new to Python programming, I highly recommend this book.