AppDividend
Latest Code Tutorials

Python Subprocess Example | Subprocess in Python

0

Python subprocess is an inbuilt module that enables you to start the new applications from your Python program. The subprocess module provides a consistent interface for creating and working with additional processes.

Python Subprocess example

Python subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. 

In the official python docs, we can read that the subprocess should be used for accessing system commands. The subprocess module enables us to spawn processes, connect to their input/output/error pipes, and receive their return codes.

The suggested approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.

The run() function was added in Python 3.5; if you need to preserve compatibility with older versions, see the Older high-level API section.

It offers a higher-level interface than some of the other available modules, and is intended to replace the functions such as os.system()os.spawn*()os.popen*()popen2.*() and commands.*()To make it easier to compare the subprocess with those other modules, many of the examples here re-create the ones used for os and popen.

Start a process in Python

You can start the process in Python using a Popen function call. The program below starts the UNIX program ‘cat’ and the second parameter is an argument. It is equivalent to ‘cat mod.py’.  You can start the program with any parameter.

Now, inside your python project folder, create two files.

  1. app.py
  2. mod.py

Inside the mod.py, write the following code.

// mod.py

student = {
  'name': 'Krunal',
  'enno': 21,
  'college': 'vvp college'
}

Now, write the following code inside the app.py file.

// app.py

from subprocess import Popen, PIPE

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

See the below output.

Python Subprocess Tutorial

The process.communicate() call reads the input and output from a process.  The stdout is a process output. The stderr will be written only if the error occurs.  If you want to wait for a program to finish you can call the Popen.wait() function.

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 the following.

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

See the following code example.

Subprocess call() method

It lists all the files and folders in the current directory.

Save process output (stdout)

We can get the output of the program and store it in the string directly using check_output. The method is defined as the following.

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

See the following example.

// app.py

import subprocess

s = subprocess.check_output(["echo", "AppDividend"])
print("s = " + s.decode('utf-8'))

See the below output.

Save process output (stdout)

Setting a shell argument to the true value causes subprocess to spawn the intermediate shell process, and tell it to run a command. The default is to run a command directly.

// app.py

import subprocess

# Command with shell expansion
subprocess.call('echo $HOME', shell=True)

See the output.

Python Subprocess Tutorial With Example

Error Handling in Subprocess

The return value from the call() function is the exit code of the program. The caller is responsible for interpreting it to detect the errors.

The check_call() function works like the call() function except that the exit code is checked, and if it indicates the error happened then the CalledProcessError exception is raised.

See the following code.

// app.py

import subprocess

subprocess.check_call(['false'])

See the output.

Error Handling in Subprocess

Conclusively, Python Subprocess Example | Subprocess in Python in Python post is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.