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
Our first method of the chapter is call().
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.
The last line shows 0, means command ran successfully.
Let us run the command with arguments.
The output is showing error.Whenever you run the call method pass the commands in Python list. Let us run the command again.
Let us discuss the last argument shell=False
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.
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.
In order to capture the output you can use check_output() method.
See the example below.
The subprocess.popen is replacing os.popen.
Let us discuss popen
class and its methods.
See the below example
=This attribute is a file object that provides output from the child process. Otherwise, it is 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).