More about the Python module subprocess and subprocess classes

3. subprocess.Popen and subprocess.PIPE classes

The class subprocess.Popen is replacing os.popen. This class uses for process creation and management in the subprocess module. It is handled by the Popen class. Syntax for subprocess.Popen class is explained below:


subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)

Execute a child program in a new process. On Unix, the class uses os.execvp() like behavior to execute the child program. On Windows, the class uses the Windows CreateProcess() function.

Real example

We can use the same df command 🙂

In [4]: disk = subprocess.Popen(['df', '-h'], stdout=subprocess.PIPE)

In [5]: diskusage = disk.communicate()

In [6]: print diskusage
('Filesystem      Size  Used Avail Use% Mounted on\n
/dev/vda1        47G  5.5G   39G  13% /\n
devtmpfs        3.8G     0  3.8G   0% /dev\n
tmpfs           3.8G     0  3.8G   0% /dev/shm\n
tmpfs           3.8G  360K  3.8G   1% /run\n
tmpfs           3.8G     0  3.8G   0% /sys/fs/cgroup\n
tmpfs           773M     0  773M   0% /run/user/0\n', None)


Did you notice the usage of communicate function in above examples? Yeah, it collect piped output from stdout or stderror and pass it to stdin. LOL it’s a good mediator..

Which means it collects the output from “subprocess.Popen” and pass it to next command with .communicate.

You will gen an idea from the above example.

This is a very vast area and I will update it going forth!!

Post navigation

Arunlal Ashok

SRE at NewFold Digital. Linux lover. Traveller. Father of two princesses.

Always happy for an open discussion! Write to arun ((@)) crybit ((dot)) com.

Leave a Reply

Your email address will not be published. Required fields are marked *