Python 阻塞和非阻塞子进程调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21936597/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Blocking and Non Blocking subprocess calls
提问by Roshan Mehta
I'm completely confused between subprocess.call(), subprocess.Popen(), subprocess.check_call(). 
我在subprocess.call(), subprocess.Popen(),之间完全混淆了subprocess.check_call()。
Which is blocking and which is not ?
哪个是阻塞的,哪个不是?
What I mean to say is if I use subprocess.Popen()whether the parent process waits for the child process to return/exitbefore it keep on its execution. 
我的意思是说,如果我使用subprocess.Popen()父进程是否在继续执行之前等待子进程到return/ exit。
How does shell=Trueaffect these calls?
如何shell=True影响这些电话?
采纳答案by unutbu
Popenis nonblocking. calland check_callare blocking.
You can make the Popeninstance block by calling its waitor communicatemethod. 
Popen是非阻塞的。call并且check_call正在阻止。您可以Popen通过调用其wait或communicate方法使实例块。
If you look in the source code, you'll see callcalls Popen(...).wait(), which is why it is blocking. 
check_callcalls call, which is why it blocks as well.
如果您查看源代码,您会看到callcall Popen(...).wait(),这就是它阻塞的原因。 
check_callcall call,这就是为什么它也会阻塞。
Strictly speaking, shell=Trueis orthogonal to the issue of blocking. However, shell=Truecauses Python to exec a shell and then run the command in the shell. If you use a blocking call, the call will return when the shellfinishes. Since the shell may spawn a subprocess to run the command, the shell may finish before the spawned subprocess. For example,
严格来说,shell=True与阻塞问题是正交的。但是,shell=True会导致 Python 执行一个 shell,然后在 shell 中运行命令。如果您使用阻塞调用,则该调用将在shell完成时返回。由于外壳可能会产生一个子进程来运行命令,外壳可能会在产生的子进程之前完成。例如,
import subprocess
import time
proc = subprocess.Popen('ls -lRa /', shell=True)
time.sleep(3)
proc.terminate()
proc.wait()
Here two processes are spawned: Popen spawns one subprocess running the shell. The shell in turn spawns a subprocess running ls.  proc.terminate()kills the shell, but the subprocess running lsremains. (That is manifested by copious output, even after the python script has ended. Be prepared to kill the lswith pkill ls.)
这里产生了两个进程: Popen 产生一个运行 shell 的子进程。shell 反过来产生一个运行的子进程ls。  proc.terminate()杀死外壳,但子进程ls仍在运行。(这是由丰富的输出表现,在python脚本结束后还是一样。准备杀ls用pkill ls。)

