Linux

Python Subprocess

The subprocess module allows you to engender new processes, connect to their input/output/error pipes, and obtain their return codes. The aim of subprocess module is to replace several older modules and functions such as os.system os.spawn* os.popen* popen2.*

call()

Our first method of the chapter is call().
Syntax
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
When you run the command in the bash shell, c shell or command prompt, whatever the case it may be. Whenever you type a command, when you run the program in terminal, The program will take standard input and display standard output. It also returns a status code, whether the program runs successfully or not. If the retrun code is 0 means command ran successfully, if return code is not 0 means something went wrong. Let us run the commands and discuss the output.
Python Subprocess
Python Subprocess
The last line shows 0, means command ran successfully.
Let us run the command with arguments.
Python Sub-process call
Python Subprocess
The output is showing error.Whenever you run the call method pass the commands in Python list. Let us run the command again.
Python Sub-process
Python Subprocess
Awesome !!
Let us discuss the last argument shell=False
Python Sub-process call
Python Subprocess
The command is giving error, because echo is not specifically a command. But it is built-in to the shell. So we let the shell=True.
Python Sub-process call
Python Subprocess
But there is warning on the Python Docs
Warning Using shell=True can be a security hazard. See the warning under Frequently Used Arguments for details.


check_output()

In order to capture the output you can use check_output() method.
See the example below.
Python Sub-process check_output
Python Subprocess

Popen

The subprocess.popen is replacing os.popen. Let us discuss popen class and its methods.
See the below example
Python Sub-process popen
Python Subprocess

Aguments stdout=subprocess.PIPE =This attribute is a file object that provides output from the child process. Otherwise, it is None.
Popen.communicate(input=None) = Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The communicate() returns a tuple (stdoutdata, stderrdata).






admin