Python

How to Use Python Subprocess Check_output Method?

In this article, we will give a brief introduction of python subprocesses and discuss how to use subprocess check_output in python. Let’s start with knowing what a sub-process is in python. Subprocess is a python module that is used to run new codes by creating new processes. It allows the user to create a new application within the currently executing python program. When the user wants to execute an external program from a C or C++ program or any external program from a git repository, the python subprocess can merge those programs. Moreover, the user can also get input, output, exit codes, or error pipes using the python subprocess. Two parameters in the function call are passed; the first parameter refers to the program which the user wants to initialize, and the other argument refers to the file arguments.

There are many subprocess modules in python, for example, subprocess.run(), subprocess.Popen(), subprocess.call(), subprocess.check_call(), subprocess.check_output(), etc. Here we are going to enlighten what is the subprocess.check_output(), what its function is, and how it is used in a python program.

The syntax of subprocess.check_output()

Every python program has standard channels for the process or subprocess. These channels are started by call() and bound to the input and output of the parent program. In other words, the command of the output of the calling program cannot be captured. Hence, the check_output() subprocess module in python is used to capture the output of the calling program for later processing. The syntax of subprocess.check_output() is as follow:

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

The ‘args’ argument of the subprocess.check_output refers to the command that is to be executed. Multiple commands can be passed to the ‘args’ argument as a string; however, they must be separated by a semicolon ‘;.’ The stdin argument refers to the value of the standard input stream that needs to be passed a pipe. The stdout argument refers to the value of the output generated from the standard output stream. The stderr argument refers to the value of error generated from the standard error stream.

The shell argument refers to the boolean parameter, which is executed through a new shell environment only when it is True. The last argument, universal_newlines is another boolean parameter. If the universal_newlines argument is True, then the file that contains stdout and stderr will open in universal newline mode. The output or the return of the subprocess.check_output() is the code of the command.

Here is an example to make you understand how the check_output() module captures the output of the calling program.

Example 1:

This simple example will produce the output code of the command.

import subprocess

calling_output = subprocess.check_output(['ls','-l'])

print (calling_output)

Text Description automatically generated

Here is the output of the given an example:

Example 2:

This example will produce the output of the calling program.

import subprocess

print (subprocess.check_output(["echo", "abc"]))

Text Description automatically generated with low confidence

Here is the output of the above code:

Example 3:

This example will demonstrate how external programs of any programming language like C, C++, Java, etc., are incorporated in a python program using subprocess in python and how check_output() will execute the output of those external programs.

This is a C program:

int main()
{
printf("Print Hello_World from C programing language");
    return 0;
}

Text Description automatically generated

Below is C++ program

#include <iostream>

using namespace std;
int main()
{
    int a, b;
cin>>a;
cin>>b;
cout<< "Print Hello_World from C++ programing language and the Values are:" << a << " " <<b;
    return 0;
}

Text Description automatically generated

This is the Java program

class HelloWorld {
    public static void main(String args[])
    {
System.out.print("Print Hello_World from Java programing language");
    }
}

Text Description automatically generated

Here is the python program that executes the above programs using subprocess in python

import subprocess
import os
 
def exeC():
    a = subprocess.check_call("gcc Hello_World.c -o out1;./out1", shell = True)
    print(", output", a)
def exeCpp():
    data, temp = os.pipe()
    os.write(temp, bytes("5 10\n", "utf-8"));
    os.close(temp)
    s = subprocess.check_output("g++ HelloWorld.cpp -o out2;./out2", stdin = data, shell = True)
    print(s.decode("utf-8"))
def exeJava():
    s = subprocess.check_output("javac HelloWorld.java;java HelloWorld", shell = True)
    print(s.decode("utf-8"))

if __name__=="__main__":
    exeC()    
    exeCpp()
    exeJava()

Text Description automatically generated

Here is the output of the above program:

Text Description automatically generated

Note: Even though the subprocess module in python is OS independent, these commands preferably need to be executed in the Linux environment. Moreover, the shell=True can become a security hazard if an untrusted input is combined, as defined in python documentation.

Conclusion:

This article is about the subprocess.check_output() module of the subprocess in python. Here we have a brief discussion of subprocesses in python and then explain the usage of the subprocess.check_output(). Let us have a quick recap of the article. The subprocess in python creates a new program to run a new code in it. It allows the user to create a new application within the currently executing python program.  There are many modules of subprograms in python, and some of them are subprocess.call(), subprocess.Popen(), subprocess.check_call(), subprocess.check_output().

The subprocess.check_output() is used to get the output of the calling program in python. It has 5 arguments; args, stdin, stderr, shell, universal_newlines. The args argument holds the commands that are to be passed as a string. The stdin, stdout, and stderr provide the input, output, and error value, respectively, from the standard stream. The shell and universal_newlines are the Boolean parameters that only execute the commands when the value of the argument is True. The return code of the command is given as the output of the subprocess.check_ouput() function. A byte string is returned as output if the code is zero; else, CalledProcessError is being raised.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content

Page was generated in 0.059404134750366