Python subprocess Module with Examples

subprocess Module:

Generally, we develop Python code to automate a process or to obtain results without requiring manual intervention via a UI form or any data-related form. But what if we need system-level information for a specific task or functionality? How do we handle system-level scripts in Python?

This is where the Python subprocess module comes into play.

The subprocess module implements several functions for running system-level scripts within the Python environment:

  • subprocess.call()
  • subprocess.run()
  • subprocess.check_output()
  • subprocess.Popen() and communicate() functions

1)subprocess.call():

To use the functions associated with the subprocess module, we must first import it into the Python environment.

The subprocess.call() function executes the command specified as arguments and returns whether the code was successfully performed or not.

Syntax:

subprocess.call(arguments , shell= True)

Example1:

In the following example, we attempt to run “echo btechgeeks” using Python scripting.

Similarly, with the call() function, the first parameter (echo) is treated as the executable command, and the arguments following the first are treated as command-line arguments.

Also, we must provide shell = True in order for the parameters to be interpreted as strings. When False is set, the arguments are interpreted as a path or file paths.

Approach:

  • Import subprocess module using the import keyword.
  • Pass “echo”, some random string, shell = True/False as the arguments to the call() function and store it in a variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import subprocess module using the import keyword
import subprocess
# Pass "echo", some random string, shell = True/False as the arguments to the call()
# function and store it in a variable.
rslt = subprocess.call(["echo", "btechgeeks"], shell=True)
# Print the above result
print(rslt)

Output:

It returns 0 as the return code, as shown below. Any other value returned by the code indicates that the command execution was unsuccessful.

"btechgeeks" 
0

Example2:

In this example, we used the Python script to run the command “ls -l.”

# Import subprocess module using the import keyword
import subprocess
rslt = subprocess.call(["ls","-l"],shell=True)
print(rslt)

Output:

0
-rw-r--r-- 1 smulani 1049033 Feb 27 10:40 check.py

2)subprocess.run():

As seen above, the call() function simply returns the code of the command executed. It does not enable us in performing a check on the input and check parameters.

For this, we have the subprocess.run() function, which allows us to execute the bash or system script within the python code and returns the command’s return code.

Additionally, it returns the arguments supplied to the function. This allows us to check the inputs to the system scripts.

For Example:

# Import subprocess module using the import keyword
import subprocess
# Pass a "echo", some random string, shell = True/False as the arguments to the run()
# function and store it in a variable.
rslt = subprocess.run(["echo", "btechgeeks"], shell=True)
# Print the above result
print(rslt)

Output:

'btechgeeks'
CompletedProcess(args=['echo', 'btechgeeks'], returncode=0)

3)subprocess.Popen() function:

The subprocess.Popen() function allows us to run child programs as a new process internally. This can also be used to run shell commands from within Python.

Syntax:

subprocess.Popen(arguments, stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)

stdout: The output returned from the command
stderr: The error returned from the command

Example:

# Import subprocess module using the import keyword
import subprocess
process = subprocess.Popen(
    ['echo', 'btechgeeks'],shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print(stdout)

Output:

b'"btechgeeks"\r\n'

We’ve also used the communicate() method here. This function allows us to read and retrieve the input, output, and error data of the script that was executed directly from the process, as shown above.