Python子进程检查调用与检查输出
我的python脚本(python 3.4.3)通过子流程调用bash脚本:Python子进程检查调用与检查输出,python,bash,ssh,subprocess,Python,Bash,Ssh,Subprocess,我的python脚本(python 3.4.3)通过子流程调用bash脚本: import subprocess as sp res = sp.check_output("bashscript", shell=True) bashscript包含以下行: ssh -MNf somehost 这将打开到某个远程主机的共享主连接,以允许后续操作 当执行python脚本时,它将提示输入ssh行的密码,但在输入密码后它将阻塞,并且永远不会返回。当我按住ctrl-C键终止脚本时,我看到连接已正确建立(
import subprocess as sp
res = sp.check_output("bashscript", shell=True)
bashscript包含以下行:
ssh -MNf somehost
这将打开到某个远程主机的共享主连接,以允许后续操作
当执行python脚本时,它将提示输入ssh
行的密码,但在输入密码后它将阻塞,并且永远不会返回。当我按住ctrl-C键终止脚本时,我看到连接已正确建立(因此ssh
line已成功执行)
当使用check\u call
而不是check\u output
时,我没有这个阻塞问题,但是check\u call
不会检索标准输出。我想了解到底是什么导致了check\u output
的阻塞行为,这可能与ssh-MNf
check\u call()
在/bin/sh
进程退出而不等待子进程时返回有关(假设shell=True
)
check_output()
等待所有输出被读取。如果ssh
继承管道,则check_output()
将等待它退出(直到它关闭继承的管道末端)
检查调用()
代码示例:
#!/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
然后等待继承管道的后台python进程退出
检查\u output()
调用Popen().communicate()
,以获取输出.communicate()
在内部调用.wait()
,即检查输出()
还等待shell退出,并检查输出()
等待EOF
如果孙辈没有继承管道,则check\u 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
start=time.time()
cmd=sys.executable+“-c”导入时间;time.sleep(2)”>/dev/null&”
子进程检查输出(cmd,shell=True)
断言(time.time()-start)<1
孙子的输出被重定向到/dev/null
,即它不继承父管道,因此检查输出()
可能会在不等待的情况下退出
注意:
&
在最后,它将孙子python进程置于后台。默认情况下,在shell=True
启动cmd.exe
的Windows上,它不起作用。太好了,谢谢您@jfs提供的详细解释
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