The Wayback Machine - https://web.archive.org/web/20240825161829/https://www.geeksforgeeks.org/python-subprocess-module/
Open In App

Python subprocess module

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The subprocess module present in Python(both 2.x and 3.x) is used to run new applications or programs through Python code by creating new processes. It also helps to obtain the input/output/error pipes as well as the exit codes of various commands. In this tutorial, we’ll delve into how to effectively use subprocessing modules to execute external functions from your Python code, pass data to them, and get results Whether you’re a beginner or an experienced Python user developer, this guide will prove useful with your skills and abilities.

An Introduction to Subprocess in Python

The subprocess module in Python is a built-in module that allows us to create new child processes. We can get exit codes, output, and error messages from these child processes. It is a valuable tool for executing external functions or commands in your Python code. Think of it as a way to programmatically interact with your computer using Python instead of manually entering commands in the terminal. This module simplifies the implementation process and seamlessly integrates external programming into your Python workflow.

For example, we can use a subprocessing module to initiate shell commands such as “ls” or “ping” and retrieve their output directly from your Python script. It also makes it easy to execute other Python scripts or executable files, such as .exe files on Windows. Also, the subprocess module gives you control over the input and output of the executed process. This means that you can accurately monitor the data sent to the application and capture the data it returns.

Uses of Subprocess Module

  • Run system commands or external programs from your Python script.
  • They can handle input, output, and errors caused by child programs in your Python code
  • Capture the output (stdout) and error messages (stderr) generated by these commands.
  • Communicate with the running process by sending input (stdin).
  • Wait for the command to complete and obtain its return code to check for success or failure.

What is subprocess Popen in Python?

`subprocess.Popen` is a low-level interface for running subprocesses, while subprocess.run is a high-level wrapper around Popen intended for ease of use. Popen allows you to start a new process and interact with its standard input, output, and error streams. It returns a handle to the running procedure that can be used to wait for the procedure to complete, check its return code, or abort it. run is a more flexible function that allows you to run a command and capture its results in a single call, allowing you to specify options for a command without having to create a Popen object and manage the streams yourself, such as whether to raise or exception if the command fails.

In general, you should use run if you just want to run the command and capture its output and Popen if you need more control over the process, such as interacting with its input and output streams. The Popen class takes the same arguments as run(), including args specifying which commands to run and other optional arguments such as stdin, stdout, stderr, shell, cwd, and env

Python Subprocess check_output

In the subprocess module, check_output is a function that closely resembles run(). It has the specific behavior of returning only the standard output of the command. However, it differs in how it handles command execution outcomes: if the command’s return code is non-zero, it triggers a CalledProcessError exception. The check_output function shares the same set of arguments as the run() function. This includes the ‘args’ parameter, which defines the command to be executed, and it also accepts additional optional arguments like ‘stdin’, ‘stderr’, ‘shell’, ‘cwd’, and ‘env’.

Python
import subprocess
try:
    ans = subprocess.check_output(["python", "--version"], text=True)
    print(ans)

except subprocess.CalledProcessError as e:
    print(f"Command failed with return code {e.returncode}")

Output
Python 3.7.17

Python Subprocess Pipe

The Python subprocess module empowers the creation and interaction with child processes, which enables the execution of external programs or commands. A standout feature of this module is the capacity to establish pipes, facilitating communication between the parent and child processes. To create such pipes, you can employ the subprocess module in combination with the Popen class. By specifying the ‘stdout’ or ‘stdin’ argument as ‘subprocess.PIPE’, you establish this interprocess communication channel. For instance, the code snippet below illustrates a pipe that connects the output of the ‘ls’ command to the input of the ‘grep’ command, which filters the output to display only the lines containing the word “file”.

Python
import subprocess

lsProcess = subprocess.Popen(["ls"], stdout=subprocess.PIPE, text=True)
grepProcess = subprocess.Popen(
    ["grep", "sample"], stdin=ls_process.stdout,
    stdout=subprocess.PIPE, text=True)
output, error = grepProcess.communicate()

print(output)
print(error)
sample_file

Python Subprocess Call

subprocess.call() is a Python function within the subprocess module. It is employed to execute a command in a separate process and wait for its completion. The function returns a return code, which is typically zero for success and non-zero for failure. This function shares its arguments with subprocess.run(), such as ‘args’ for specifying the command to be executed, along with optional parameters like ‘stdin’, ‘stdout’, ‘stderr’, ‘shell’, ‘cwd’, and ‘env’.

By default, the command’s standard output and error are directed to the same output streams as the parent process unless you explicitly redirect them using the ‘stdout’ and ‘stderr’ arguments.

Python
import subprocess
ans = subprocess.call(["python", "--version"])
if ans == 0:
    print("Command executed.")
else:
    print("Command failed.", return_code)

Output
Python 3.7.17
Command executed.

Compile and Run Different Languages in Python using Subprocess

To execute different programs using Python two functions of the subprocess module are used:

1.subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
Parameters:
args=The command to be executed.Several commands can be passed as a string by separated by “;”.
stdin=Value of standard input stream to be passed as (os.pipe()).
stdout=Value of output obtained from standard output stream.
stderr=Value of error obtained(if any) from standard error stream.
shell=Boolean parameter.If True the commands get executed through a new shell environment.
Return Value:
The function returns the return code of the command.If the return code is zero, the function simply returns(command executed successfully) otherwise CalledProcessError is being raised.

2.subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
Parameters:
args=The command to be executed. Several commands can be passed as a string by separated by “;”.
stdin=Value of standard input stream to be passed as pipe(os.pipe()).
stdout=Value of output obtained from standard output stream.
stderr=Value of error obtained(if any) from standard error stream.
shell=boolean parameter.If True the commands get executed through a new shell environment.
universal_newlines=Boolean parameter.If true files containing stdout and stderr are opened in universal newline mode.
Return Value:
The function returns the return code of the command.If the return code is zero, the function simply returns the output as a byte string(command executed successfully) otherwise CalledProcessError is being raised.

Example: Let us consider the following code example in different languages.

C++
#include <iostream> 
using namespace std; 
int main() 
{ 
    int a, b; 
    cin >> a >> b; 
    cout << "Hello World from C++.Values are:" << a << " " << b; 
    return 0; 
} 
C
#include<stdio.h> 
int main() 
{ 
    printf("Hello World from C"); 
    return 0; 
} 
Java
class HelloWorld { 
    public static void main(String args[]) 
    { 
        System.out.print("Hello World from Java."); 
    } 
} 

Output
Hello World from C++.Values are:0 4196176

Python Code to Execute the Above Programs

In this code there are three functions created separate each for executing C,C++ and JAVA program respectively. ‘executeC()’ is used to execute the C program file.‘executeCpp()’ is used to execute the C++ program file.‘executeJava()’ is used to execute the JAVA program file.

In each method It employs the ‘subprocess.check_call’ method to execute the necessary compilation and execution commands. After execution, it prints the return code, which can indicate whether the program ran successfully.

Python
# Python 3 program to demonstrate subprocess
import subprocess
import os

def excuteC():
    # store the return code of the c program(return 0)
    # and display the output
    s = subprocess.check_call("gcc HelloWorld.c -o out1;./out1", shell=True)
    print(", return code", s)

def executeCpp():
    # create a pipe to a child process
    data, temp = os.pipe()
    # write to STDIN as a byte object(convert string
    # to bytes with encoding utf8)
    os.write(temp, bytes("5 10\n", "utf-8"))
    os.close(temp)

    # store output of the program as a byte string in s
    s = subprocess.check_output(
        "g++ HelloWorld.cpp -o out2;./out2", stdin=data, shell=True)

    # decode s to a normal string
    print(s.decode("utf-8"))

def executeJava():
    # store the output of
    # the java program
    s = subprocess.check_output(
        "javac HelloWorld.java;java HelloWorld", shell=True)
    print(s.decode("utf-8"))


# Driver function
if __name__ == "__main__":
    excuteC()
    executeCpp()
    executeJava()

Output

Hello World from C, return code 0
Hello World from C++. Values are:5 10
Hello World from Java.


Python subprocess module – FAQs

What is the Python Subprocess Module?

The Python subprocess module is a standard utility module that allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module is intended to replace older modules and functions like os.system, os.spawn, os.popen, popen2, and commands. It provides more powerful facilities for spawning new processes and retrieving their results.

Is Subprocess Part of Python Standard Library?

Yes, the subprocess module is part of the Python standard library. It is included with Python and does not require any additional installation.

What is the Difference Between Import and Subprocess in Python?

  • Import: The import statement in Python is used to bring modules into the current namespace so that you can access functions, classes, and variables defined within those modules. It’s a fundamental feature of Python that allows code modularization and reusability.
  • Subprocess: subprocess is a specific module within the Python standard library used for creating and managing additional processes. It provides the capability to spawn new processes, connect to their input/output/error pipes, and retrieve their results. It is not related to the import statement except that you need to import the subprocess module to use its functionality.

What is the Difference Between os and Subprocess in Python?

  • os: The os module provides a way of using operating system dependent functionality like reading or writing to the filesystem, managing paths, and accessing environment variables. It includes some functions for process management as well, such as os.system which allows you to run shell commands, but it is more limited.
  • subprocess: The subprocess module is specifically designed for spawning new processes, connecting to their input/output/error pipes, and obtaining their return codes. It offers more control and flexibility than os.system by allowing interaction with the process’s input and output.

Is Subprocess Run Synchronous?

Yes, by default, the subprocess.run() function is synchronous, meaning it waits for the command to complete and returns a CompletedProcess instance. It blocks the calling thread until the process whose creation it has requested has completed, and then it proceeds with the rest of the code. If you need asynchronous behavior, you can use subprocess.Popen which provides more control over how processes are run, including non-blocking behavior.

These explanations clarify the functionality and utility of the subprocess module in Python, distinguishing it from other similar modules and concepts within the language



Similar Reads

How to Navigating the "Error: subprocess-exited-with-error" in Python
In Python, running subprocesses is a common task especially when interfacing with the system or executing external commands and scripts. However, one might encounter the dreaded subprocess-exited-with-error error. This article will help we understand what this error means why it occurs and how to resolve it with different approaches. We will also p
4 min read
Handling Access Denied Error Occurs While Using Subprocess.Run in Python
In Python, the subprocess module is used to run new applications or programs through Python code by creating new processes. However, encountering an "Access Denied" error while using subprocess.run() can be problematic. This error arises due to insufficient permissions for the user or the Python script to execute the intended command. In this artic
5 min read
Retrieving the output of subprocess.call() in Python
The subprocess.call() function in Python is used to run a command described by its arguments. Suppose you need to retrieve the output of the command executed by subprocess.call(). In that case, you'll need to use a different function from the subprocess module, such as subprocess.run(), subprocess.check_output(), or subprocess.Popen(). Introduction
4 min read
Os Module Vs. Sys Module In Python
Python provides a lot of libraries to interact with the development environment. If you need help using the OS and Sys Module in Python, you have landed in the right place. This article covers a detailed explanation of the OS and Sys Module including their comparison. By the end of this article, you will be able to easily decide which module suits
5 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Python calendar module : formatmonth() method
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. class calendar.TextCalendar(firstweekday=0) can be used to generate plain text
2 min read
Python | Writing to an excel file using openpyxl module
Prerequisite : Reading an excel file using openpyxl Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files. For example, user might have to go through thousands of rows and pick out few handful information to make small changes b
3 min read
median() function in Python statistics module
Python is a very popular language when it comes to data analysis and statistics. Luckily, Python3 provide statistics module, which comes with very useful functions like mean(), median(), mode() etc.median() function in the statistics module can be used to calculate median value from an unsorted data-list. The biggest advantage of using median() fun
4 min read
Stack and Queue in Python using queue Module
A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generally created in languages such as C/C++ and Java. 1.
3 min read
PyMsgBox module in Python
PyMsgBox is simple, cross-platform, purely implemented in Python for message boxes as JavaScript has. It uses Python's built-in Tkinter module for its GUI. Installation This module does not built-in Python. To install it type the below command in the terminal. pip install PyMsgBox There are four functions in PyMsgBox, which follow JavaScript’s mess
2 min read
uniform() method in Python Random module
uniform() is a method specified in the random library in Python 3. Nowadays, in general, day-day tasks, there's always the need to generate random numbers in a range. Normal programming constructs require a method more than just one word to achieve this particular task. In python, there's an inbuilt method, "uniform()" which performs this task with
2 min read
mode() function in Python statistics module
The mode of a set of data values is the value that appears most often. It is the value at which the data is most likely to be sampled. A mode of a continuous probability distribution is often considered to be any value x at which its probability density function has a local maximum value, so any peak is a mode.Python is very robust when it comes to
5 min read
Reading an excel file using Python openpyxl module
Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files.For example, users might have to go through thousands of rows and pick out a few handful of information to make small changes based on some criteria. Using Openpyxl module, t
3 min read
median_low() function in Python statistics module
Median is often referred to as the robust measure of the central location and is less affected by the presence of outliers in data. statistics module in Python allows three options to deal with median / middle elements in a data set, which are median(), median_low() and median_high(). The low median is always a member of the data set. When the numb
4 min read
median_high() function in Python statistics module
Median is often referred to as the robust measure of the central location and is less affected by the presence of outliers in data. statistics module in Python allows three options to deal with median / middle elements in a data set, which are median(), median_low() and median_high(). The high median is always a member of the data set. When the num
4 min read
median_grouped() function in Python statistics module
Coming to Statistical functions, median of a data-set is the measure of robust central tendency, which is less affected by the presence of outliers in data. As seen previously, medians of an ungrouped data-set using median(), median_high(), median_low() functions. Python gives the option to calculate the median of grouped and continuous data functi
4 min read
stdev() method in Python statistics module
Statistics module in Python provides a function known as stdev() , which can be used to calculate the standard deviation. stdev() function only calculates standard deviation from a sample of data, rather than an entire population. To calculate standard deviation of an entire population, another function known as pstdev() is used. Standard Deviation
5 min read
Python | Working with .docx module
Word documents contain formatted text wrapped within three object levels. Lowest level- Run objects, Middle level- Paragraph objects and Highest level- Document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. 1. The first step is to instal
3 min read
Plotting graphs using Python's plotly and cufflinks module
plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. cufflink connects plotly with pandas to create g
2 min read
Python | ASCII art using pyfiglet module
pyfiglet takes ASCII text and renders it in ASCII art fonts. figlet_format method convert ASCII text into ASCII art fonts. It takes following arguments : text font ( DEFAULT_FONT = 'standard' ) Command to install pyfiglet module : pip install pyfiglet Code #1: Text in default font # import pyfiglet module import pyfiglet result = pyfiglet.figlet_fo
6 min read
easyinput module in Python
easyinput module in Python offers an easy input interface analogous to cin stream in C++. It supports multiple data types including files and provides functionalities such as input till different data types, multi-line input, etc. Installation To install this module type the below command in the terminal. pip install easyinputFunction Usedread(*typ
3 min read
Python | Adjusting rows and columns of an excel file using openpyxl module
Prerequisites : Excel file using openpyxl writing | reading Set the height and width of the cells:Worksheet objects have row_dimensions and column_dimensions attributes that control row heights and column widths. A sheet’s row_dimensions and column_dimensions are dictionary-like values; row_dimensions contains RowDimension objects and column_dimens
3 min read
Python | Plotting charts in excel sheet using openpyxl module | Set - 1
Prerequisite: Reading &amp; Writing to excel sheet using openpyxl Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Let's see how to plot different charts using realtime data. Charts are composed of at least one series of one or more data poi
6 min read
Python | Plotting charts in excel sheet using openpyxl module | Set – 2
Prerequisite: Python | Plotting charts in excel sheet using openpyxl module | Set – 1 Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Charts are composed of at least one series of one or more data points. Series themselves are comprised of
6 min read
Python | Plotting charts in excel sheet using openpyxl module | Set 3
Prerequisite : Plotting charts in excel sheet using openpyxl module Set - 1 | Set – 2Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Charts are composed of at least one series of one or more data points. Series themselves are comprised of r
7 min read
Python | Create and write on excel file using xlsxwriter module
XlsxWriter is a Python module for writing files in the XLSX file format. It can be used to write text, numbers, and formulas to multiple worksheets. Also, it supports features such as formatting, images, charts, page setup, auto filters, conditional formatting and many others.Use this command to install xlsxwriter module: pip install xlsxwriter Not
3 min read
spwd module in Python
spwd module in Python provides access to the Unix shadow password database. The entries stored in the database is tuple-like objects whose attributes are similar as the members of spwd structure defined in &lt;shadow.h&gt; header file. Following are the attributes of tuple-like object which represents the entries stored in Unix shadow password data
5 min read
Pygorithm module in Python
Pygorithm module is a Python module written purely in Python and for educational purposes only. One can get the code, time complexities and much more by just importing the required algorithm. It is a good way to start learning Python programming and understanding concepts. Pygorithm module can also help to learn the implementation of all major algo
2 min read
Python | Plotting Area charts in excel sheet using XlsxWriter module
Prerequisite: Create and write on an excel file XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different charts using realtime data. Charts are composed of at least one series of one or more data points. Series the
6 min read
Practice Tags :