check_call()
尽快返回/bin/sh
进程退出而不等待后代进程(假设shell=True
就像你的情况一样)。
check_output()
等待直到读取所有输出。如果ssh
然后继承管道check_output()
将等待直到它退出(直到它关闭其继承的管道末端)。
check_call()
代码示例:
#!/usr/bin/env python
import subprocess
import sys
import time
start = time.time()
cmd = sys.executable + " -c 'import time; time.sleep(2)' &"
subprocess.check_call(cmd, shell=True)
assert (time.time() - start) < 1
未读取输出;check_call()
立即返回,无需等待孙子后台python进程。
check_call()
只是Popen().wait()
. Popen()
启动外部进程并立即返回,无需等待其退出。.wait()
收集进程的退出状态——它不等待其他(孙子)进程。
如果读取输出(它被重定向并且孙子 python
进程继承了 stdout 管道):
start = time.time()
subprocess.check_output(cmd, shell=True)
assert (time.time() - start) > 2
然后它会等待,直到继承管道的后台python进程退出。
check_output()
calls Popen().communicate()
,得到输出。.communicate()
calls .wait()
内部即check_output()
还等待 shell 退出并check_output()
等待EOF。
如果孙子没有继承管道那么check_output()
不等待它:
start = time.time()
cmd = sys.executable + " -c 'import time; time.sleep(2)' >/dev/null &"
subprocess.check_output(cmd, shell=True)
assert (time.time() - start) < 1
孙子的输出被重定向到/dev/null
即,它不继承父级的管道,因此check_output()
可以不等待就退出。
Note: &
最后将孙子 python 进程置于后台。它不能在 Windows 上运行shell=True
starts cmd.exe
默认情况下。