Today, I learned that Python calls the shell through a child process, feeling that the tutorial is too complicated, there are some fundamentally useless features, such as redirecting input and output, the shell itself is supported, there is no need to use the Python API. Decide yourself to summarize under.
In fact, there are only two kinds:
The first is a simple call, in which case the parent process waits for the child process to complete and the return value is the exit information, as an example:
# Import sub-process package Import subprocess # simple call, can write multiple shell statements, separated by semicolons, you can redirect the shell-side output to text for Python to read, R returns 0 instructions to run the normal R=subprocess.call ("CD. /;ls|wc-l >r.txt 2>&1", Shell=true)
The second is a full call, using the Popen class, and the previous simple call is actually encapsulated with Popen. Popen The default parent process does not wait for the child process to complete, but can be set through parameters, for example:
Child=subprocess. Popen ("ping-c 5 www.baidu.com", shell=True)print'Parent Process'
When using Popen, you can add the Child.wait () method if you want the parent process to wait for the child process to finish executing.
Some other methods/properties are listed below
Child.pid #子进程pid
Child.poll () #检查子进程状态
Child.kill ()/child.terminate () #终止子进程
Child.send_signal () #向子进程发送信号
Python Call Shell