The module subprocess in Python

Now we all are aware about “What is Python?” and “How to write a Hello World code?” No problem, if you do not know, please read this post >> Introduction to Python – Say Hello World! << before starting about “subprocess.” You will get a brief idea from there.

What is subprocess module? Why this module has a great job with Linux?

As we are SysAdmins, we need the advantageous of Python in Shell. We need it to simplify our jobs with Python. Yup, I am here to help you with my little knowledge 🙂

Okay, let’s move with the module “subprocess.” This is a Python module for administration tasks. This module should be used for accessing system commands. This is the simplest way of running Linux commands Yeah, that’s really what we need!

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

This module intends to replace several older modules and functions such as listed below:

os.system
os.spawn*
os.popen*
popen2.*
commands.*

Syntax

This is the default syntax of subprocess module. It runs the command described by args. Wait for command to complete, then return the returncode attribute. The default value for shell is False and is not recommended to use True value if you are not very much confidence about the input.

What is the difference between shell=False and shell=True in Python subprocess.call?

In shell=True, the specified command in the syntax will be executed through the Shell. This should be helpful, if you want to integrate other shell features like shell pipes, filename wildcards, environment variable expansion, and expansion of ~ to a user’s home directory into the existing code.

When shell=True is dangerous?

If we execute shell commands that might include unsanitized input from an untrusted source, it will make a program vulnerable to shell injection, a serious security flaw which can result in arbitrary command execution. For this reason, the use of shell=True is strongly discouraged in cases where the command string is constructed from external input.