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:

Syntax

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)

Popen.communicate()

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 A

Senior System Developer at Zeta. Linux lover. Traveller. Let's connect! Whether you're a seasoned DevOps pro or just starting your journey, I'm always eager to engage with like-minded individuals. Follow my blog for regular updates, connect on social media, and let's embark on this DevOps adventure together! Happy coding and deploying!

Leave a Reply

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