×

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

NSE Tools In Python

About NSE NSE (National Stock Exchange) of India Limited is the advanced stock exchange of India. It is located in Mumbai, Maharastra and It was organized in 1992. It was...

2 minutes read.

Python MySQL Update Operation

Python MySQL Update Operation: In this part of tutorial, we will learn that how can we update a table present in SQL database through our Python program. As like SQL,...

4 minutes read.

Python Line Break

Introduction In this tutorial, you will learn line breaks in python.In Python, the new line character is used to indicate the start of a new line and the end of an...

5 minutes read.

Python int()

Python int() class The int() class in Python returns an integer object constructed from a number or string x. Syntax class int(x, base=10) Parameter x: This parameter represents a number or a string that can be converted into...

1 minute read.

Python email utils

Python is a popular programming language in this growing world. There are many resources to learn python online without spending a single penny. In this article, we will talk about a...

4 minutes read.

Difference between Python 2 and Python 3

In this tutorial, we will learn the differences between two versions of python, that is, python version 2 and python version 3. Some basic differences include- Python 2 is the older version...

3 minutes read.

Python program to find Fibonacci series

Python program to find Fibonacci series A Fibonacci series is an integer sequence of 0, 1, 1, 2, 3, 5, 8.... We can identify the Fibonacci series as any number sequence...

2 minutes read.

CatPlot in Python

Python Seaborn Library Seaborn is a superb Python tool for displaying graphical statistics graphing. Seaborn provides different color schemes and attractive default styles to facilitate the creation of various statistics charts...

8 minutes read.

BOTTLE Python Web Framework

The Bottle is a lightweight WSGI micro web framework for python. It acts like a thin wrapper around a web server where it is distributed as a single file module...

4 minutes read.

Python hasattr() function

Python hasattr() function The hasattr() function in Python returns a Boolean value ‘True’ if the given object has the specified attribute, else it returns False. Syntax hasattr(object, name) Parameter object: it is a required parameter which represents an object. attribute:...

1 minute read.

Python Memory Management

In order to manage memory, Python uses a private heap that contains all of its data structures and objects. The Python memory manager is responsible for the internal management of...

11 minutes read.

Sort Dictionary in Python

Dictionaries In Python, a dictionary is an unordered collection or set of data types that enable of store data in an unordered key-value/pair. The key is stored alongside with value. Dictionary contains key:...

4 minutes read.

Python String endswith() method

Python String endswith() method The string.endswith() method in Python returns a Boolean value True if the string ends with the specified suffix, otherwise it returns False. Syntax endswith(suffix[, start[, end]]) Parameter suffix – This parameter represents a string or tuple...

2 minutes read.

Python Packages

A package is a collection of Python modules that share a similar namespace and are generated by putting all of the modules in a single directory with certain special files...

6 minutes read.

Python Namespace

In python, the namespace is a very important concept that should be understood before using any function or variables. When we write code, we often use variables, libraries, functions, modules, etc....

4 minutes read.

Exclusive OR in Python

In Python, the exclusive OR (XOR) operator is represented by the caret symbol (^). It compares each bit of the first operand to the corresponding bit of the second operand,...

3 minutes read.

API Requests using Python

What is an API? API stands for Application Programming Interface. It is commonly known as API. It provides an environment that helps two or more computer programs to contact each other....

5 minutes read.

Python enumerate() function

Python enumerate() function The enumerate() function in Python takes a collection (e.g. a tuple) and returns it as an enumerate object. Syntax: enumerate(iterable, start=0) Parameter Iterable:  This parameter represents an iterable object start:    This parameter represents a number defining...

1 minute read.

Self in Python

 “self" is neither a keyword nor has a special meaning in Python, but it has a place and a job to do in Object-oriented programming. When we create a class...

6 minutes read.

How To Take Multiple Inputs In Python

In C language, we make use of the scanf() function to obtain the values from the user and store it in the variable. Coming to the Python language, we use the...

5 minutes read.