Python provides a lot of functionalities with different modules and libraries. When we need to open a 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
Start with call Function
The simples use case to create a subprocess is using
call() function accepts related binary or executable name and parameters as Python list. In this example, we will call Linux
ls command with
Create Own Shell For Process
While creating a new process the newly created process will use current python shell and associated variables. We can specify the to create a new shell with the
shell=True like below.
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 a Python shell for our examples. We can save the process output to a Python variable by calling
check_output command like below. In this example, we will save.
We can see that all created output is saved into the variable named
output. When we try to print this variable content to the terminal we will see the exact run command output which is the file list with a user, owner and access time information.
Convert Output To A String Instead of Byte Array
In the previous example, we have seen that the output is not a formatted state because the output is saved as a byte array into the
output variable. We will provide the output as a string by using
universal_newlines option as true for
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
p = subprocess.Popen(["echo", "hello poftut"], stdout=subprocess.PIPE) print(p.communicate())
Throw Exception If Run Command Has Error
While running commands with the
call() function we may get some error related with the provided command. The error will be printed to the screen like a regular output for the Python.
This may be misinterpreted like the command is completed successfully and without error, so the output is printed to the screen. If we want to create some watchdog about command errors we can use
check option which will raise an exception if the command has errors.
We can see that there is an error