×

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

How to Create an Array in Python?

How to Create an Array in Python In the previous article, we have discussed how to declare an array in Python. So, let's have a quick revision of that, and then we...

5 minutes read.

Program of Cumulative Sum in Python

Introduction This tutorial, explains what is meant by lists, the cumulative total, several approaches to calculating the cumulative sum of digits in a list, etc. Learn the straightforward Python codes for...

5 minutes read.

OSError in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

4 minutes read.

Python Sys Stdout

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Inheritance in Python

Inheritance in Python Object-Oriented Programming provides reusable patterns to the code for restricting the redundancy in development projects. One of the basic principles of Object-Oriented Programming that helps achieve recyclable code...

8 minutes read.

Python Slice from Last Occurrence of K

Introduction We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on...

3 minutes read.

Continue and Pass Statements in Python

Difference between continue and pass statements in Python The tasks can be repeated and automated efficiently using loops in Python. Sometimes we have to exit from the entire loop completely, we...

2 minutes read.

Write Dictionary to CSV in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

4 minutes read.

One Liner If-Else Statements in Python

Before learning one liner if else Python, let us first know what Python is. Python is a broadly helpful, object-oriented and dependable language having a large number of utilizations from...

4 minutes read.

Python | a += b is not always a = a + b

a += b in Python doesn't always behave the same way as a = a + b; the same operands can produce different outcomes depending on the circumstances. But we...

3 minutes read.

Python Strong Number

Strong Number- Logic Divide each of the number's digits into separate units to determine if it is a strong number or not.The factorial of each digit must then be determined. The...

5 minutes read.

Difference Between Python and Scala

What is Python? Python is a high-level general-purpose interpreted programing language. It is used for multi general-purpose work such as language construct as well as its object-oriented approach aims to help...

4 minutes read.

Python String ljust() method

Python String ljust() method The string.ljust() method in Python will left align the string, where the padding is done using the parameter fillchar (space is default). Syntax String.ljust(width[, fillchar]) Parameter width: This parameter represents the...

2 minutes read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

How to find square root in python

How to find Square Root of a number In Python Python makes a lot of tasks easier by using different functions, modules, and libraires. There is an inbuilt function in Python...

6 minutes read.

Python Dictionary update() method

Python Dictionary update() method The dictionary.update() method in Python inserts the specified items to the dictionary. Syntax dictionary.update(iterable) Parameter iterable- This parameter represents a dictionary or an iterable object with key value pairs, that will...

1 minute read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

Not supported between instances of str and int in python

In this article, you are going to learn why the type error occurs between instances of string and integer datatypes. Also, you will know what kind of error is the...

6 minutes read.

Nested List in Python

The list is an inbuilt sequential data type in Python. It is a very useful and frequently used data type. A list can store any number of data items of...

4 minutes read.

Python IDE

What is an IDE?  An IDE or an Integrated Development Environment is a type of software where developers can develop many software’s and applications and run the programs inside it. An...

11 minutes read.