Python subprocess.Popen() is one of best way to call external application in python. It has two main advantages:
1.It can return the output of child program, which is better than os.system().
2.It can return the output of child program with byte type, which is better an os.popen().
In this tutorial, we will introduce python beginners how to use this function correctly and get the output of child program.
Preliminary
We import os library first.
import os
Create a command line
We will use subprocess.Popen() to run other applications, a command line (cmd) should be created.
For example:
cmd = r'c:\aria2\aria2c.exe -d f:\ -m 5 -o test.pdf https://example.com/test.pdf'
In this tutorial, we will execute aria2c.exe by python.
Execute a Child Program
We can use subprocess.Popen() to run cmd like below:
p1=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)
Here we set stdout=subprocess.PIPE, which means we will get the cmd output.
Get child program output
subprocess.Popen() will return the output of child program, we can read this output line by line.
msg_content = '' for line in p1.stdout: print(line) l = line.decode(encoding="utf-8", errors="ignore") msg_content += l p1.wait() print(msg_content)
p1.wait() is very important, which will block python main process to read full output of child program.
Run this code, you may get the result.
From the result, we can find subprocess.Popen() will return the output of cmd with byte mode, we can convert it to string with encoding utf-8.
l = line.decode(encoding="utf-8", errors="ignore")
This will avoid UnicodeDecodeError.