Python Subprocess and Popen with Examples

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/python-subprocess-popen-examples/
PINTEREST
PINTEREST
INSTAGRAM

Python provides a lot of functionalities with different modules and libraries. When we need to open new process inside a Python application we can use subprocess library and related functions.

Import subprocess Module

In order to use related functions and libraries we should import the subprocess library.

Start with call Function

The simples use case to create a subprocess is using call() function. call() function accepts related binary or executable name and parameters as Python list. In this example we will call Linux ls command with -l and -a parameters.

Start with call Function

Start with call Function

Create Own Shell For Process

While create new process the newly created process will use current python shell and associated variables. We can specify the to create new shell with the shell=True like below.

Create Own Shell For Process

Create Own Shell For Process

Save Process Output (stdout)

After running given command or binary some output may be created. By default this output is printed to the stdout which is Python shell for our examples. We can save the process output to an Python variable by calling check_output command like below. In this example we will save

Save Process Output (stdout) 

Save Process Output (stdout) 

Get Data From Process

We can communicate with the process by opening the process with Popen() function. We will set the created process instance into a variable and then use communicate() function which will read the process pipe. In this example we will put hello poftut with the echo command into a pipe and then read with communicate()

Get Data From Process

Get Data From Process

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/python-subprocess-popen-examples/
PINTEREST
PINTEREST
INSTAGRAM

LEARN MORE  Killing Linux Processes With killall Command

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)