×

Subprocess in Python

In this tutorial, we will understand what is a subprocess in python and will understand how to use it.

Subprocess

A subprocess is a very prevailing portion of the python library. It is a module present in python that is used to run any new application or program by writing python codes. Moreover, it is also helpful in acquiring the input or output or error pipes or even the exit codes of several commands.

Under the subprocess module, two functions are used to implement dissimilar programs using Python. Let us understand each of these functions one by one.

1.Let us first understand the first function

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


Now, let us understand the Parameters used in the above method:args = It denotes the argument to be used in the program. It consists of the command to be implemented as a parameter. Numerous commands can be passed as a string but they should be separated by a semi-colon “;”.

stdin = It denotes the value of the standard input stream to be passed as (os.pipe ()).
stdout = It denotes the value of the output obtained from the standard output stream.

stderr = It denotes the value of fault obtained (if any) from the standard error stream.

shell = It denotes the boolean parameter. If the value returned is True then commands get executed through a new shell environment.

Return Value:
The return code of the command is returned by the above function. If the return code is zero, then the function simply returns (command executed successfully), or else an error named CalledProcessError is being arisen.

2. Let us understand the second function.

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


Now, let us understand the Parameters used in the above method:

args = It denotes the argument to be used in the program. It consists of the command to be implemented as a parameter. Numerous commands can be passed as a string but they should be separated by a semi-colon “;”.

stdin = It denotes to the value of standard input stream to be passed as pipe(os.pipe()).

stdout = It denotes the value of output obtained from the standard output stream.

stderr = It denotes the value of error obtained (if any) from the standard error stream.

shell = It denotes the boolean parameter. If True the commands get executed through a new shell environment.

universal_newlines = Boolean parameter. If the value is true then, files containing stdout and stderr are unlocked in universal newline mode.

Return Value:
The return code of the command is returned by the above function. The function just returns the output as a byte string (command accomplished) if the return code is zero otherwise an error named CalledProcessError is being raised.

Let us now see the example to understand the concept better.

Considering a C program

Example 1:

#include<stdio.h>
int main ()
{
	printf(" Bonjour world from C ");


	// It would result in an exception when returned with any other non zero 
	// value when called from python
	return 0;
}

Considering a C++ program

Example 2:


#include <iostream>
using namespace std;
int main ()
{
	int a1, a2;
	cin >> a1 >> a2;
	cout << " Bonjour world from C++. Values are:" << a1<< " " << a2;
	return 0;
}

Considering a JAVA program

Example 3:


class Bonjour {
	public static void main (String args[])
	{
		System.out.print ("Bonjour world from Java.");
	}
}






# Python 3 program to illustrate the usage of the subprocess module


import subprocess
import os


def excuteC():


	# The return code of the c program(return 0) is stored 
	# and the result is displayed
	sp = subprocess.check_call("gcc BonjourWorld.c -o out1;./out1", shell = True)
	print(", return code", sp)


def executeCpp():


	# creating a pipe to a child process
	data, temp = os.pipe()


	# writing to STDIN as a byte object (converting the string
	# to bytes with encoding utf8)
	os.write (temp, bytes("25 70\n", "utf-8"));
	os.close (temp)


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


	# decoding to a usual string
	print(sp.decode("utf-8"))


def executeJava():


	# storing the result of
	# the java program
	sp= subprocess.check_output("javac BonjourWorld.java;java HelloWorld", shell = True)
	print(sp.decode("utf-8"))




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

Output:

Subprocess in Python

Related Topics

Make Notepad using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

5 minutes read.

How to Install Matplotlib in Python?

How to Install Matplotlib in Python The speed at which the enormous amount of data is generating has become a huge aid in understanding what's going on currently in the market....

4 minutes read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Find Median of List in Python

The median is an enlightening measurement that is utilized as a proportion of the focal inclination of a circulation. It is equivalent to the centre worth of the conveyance. There...

3 minutes read.

OS Module in Python

What is a module? The Modules are the kind of files that contains python statements and definitions. The module is known by the name of the file followed by the suffix...

8 minutes read.

Python CGI Programming

The Concept of CGI CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set of rules (specification) that establishes a dynamic interaction between...

9 minutes read.

Python Comments

In this tutorial, we will discuss the importance of comments in the Python code and how various types of comments can be inserted in the code. Comments are used to describe...

3 minutes read.

Python TCP Server

The TCP server library is also known as the socket library. Socket programming is the method of connecting two nodes through a network to form communication between two nodes. In...

3 minutes read.

Python Interface

When creating an application, it is important to continuously keep track of its changes. As an application grows, sometimes it gets hard to manage its updates and changes. Often, you...

4 minutes read.

Python property()

Python property() class The property() class in Python returns a property attribute. Syntax class property(fget=None, fset=None, fdel=None, doc=None) Parameter fget: This attribute is used for getting an attribute value. fset : This parameter sets an attribute value. fdel: It is a function for deleting...

1 minute read.

Front end in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

4 minutes read.

GUI Calendar using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Difference between For Loop and While Loop in Python

What is the “For” loop? The “For” Loop is a commonly used control structure in programming that allows us to repeat a set of actions multiple times. The “For” loop is...

3 minutes read.

Python SymPy

A Python package for symbolic mathematics is called SymPy. Its goal is to develop into a fully-fledged computer algebra system (CAS) while maintaining the code as straightforward as possible to...

3 minutes read.

How to Concat two Dataframes in Python

Using Pandas dataframe, we can concat two dataframes or series in Python. So let's take a brief introduction to what is Pandas in Python. Pandas is a library typically used for...

7 minutes read.

Python Syntax Error Invalid Syntax

Python is renowned for its simple and direct syntax. However, we might come across some things that Python doesn't allow if we are learning Python for the very first time or if...

14 minutes read.

Python hash() function

Python hash() function The hash() function in Python returns the hash value of the object (if it has one).  Syntax hash(object) Parameter obj : This parameter represents the object which we need to convert into hash. Return This...

1 minute read.

Is Python Case-sensitive when Dealing with Identifiers

Yes, Python is a case-sensitive language while dealing with identifiers. Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. It is a case-sensitive...

6 minutes read.

Python Switch Case

What is a Switch Case Statement? In the programming languages, a switch statement is a logical loop or syntax that tests the variable's value and compares it with multiple cases. Once...

3 minutes read.

Python Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.