Python subprocess is a module in python that helps us to execute shell commands, get the input/output/error pipes, and the error codes for the executed command from the python language.
Why Python Subprocess Module?
Do you know any other module in python which can help us to execute the shell commands? Your answer will be the ‘os’ module in python.
The os.system() can help us to execute the shell commands from the python program but the problem is that we cannot get the output of the executed command in our python program.
os.system()
>>> import os
>>> os.system('ls')
main.py requirements.txt venv
The output is generated at the terminal. We can only retrieve the error code for the executed shell command.
Example:
Error code in os.system()
import os
out = os.system('ls')
>>> print(out)
0
One way to get the output of the executed shell command is by using the pipeline operator to store the output in a text file and then read the file in the python program.
Example:
os.system() pipeline
import os
os.system('ls > output.txt')
file = open('output.txt','r')
>>> print(file.read())
output.txt
main.py
requirements.txt
venv
Python subprocess module is a high-level interface for executing shell commands from the python program and is intended to replace the following python modules and functions:
os.system()
*os.spawn()
os.popen()
popen2.()
commands.()
According to the python official documentation, the subprocess module will rule these previously stated functions as they are going to be deprecated very soon.
Now when you know why to choose subprocess in python and what functions it is going to replace. So let’s learn about Python Subprocess Module.
Python Subprocess Run Function
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)
The subprocess.run() function was added in Python 3.5 and it is recommended to use the run() function to execute the shell commands in the python program.
The args argument in the subprocess.run()
function takes the shell command and returns an object of CompletedProcess in Python.
Example:
CompletedProcess Object
out = subprocess.run('ls', shell=True)
>>> print(out)
CompletedProcess(args='ls', returncode=0)
Learn more about Python Subprocess from the original Post. Read more.
Top comments (0)