Python 为什么subprocess.Popen.wait使用忙循环?

Python 为什么subprocess.Popen.wait使用忙循环?,python,subprocess,Python,Subprocess,如文档所述,Popen.wait不执行繁忙等待。我相信一些操作系统有系统调用来等待进程结束,而不需要繁忙的循环。为什么没有利用这些机制?我并不完全肯定。我不认为有一种方法可以让waitpid或类似的东西有一个完全非侵入性的同步超时。另外,我认为一些Unice对于waitpid如何处理信号有不同的规则 评论说他们从Thread.wait中窃取了循环,而threading.py中的评论则表明它用于响应 from subprocess import Popen, PIPE handle = Pope

如文档所述,Popen.wait不执行繁忙等待。我相信一些操作系统有系统调用来等待进程结束,而不需要繁忙的循环。为什么没有利用这些机制?

我并不完全肯定。我不认为有一种方法可以让waitpid或类似的东西有一个完全非侵入性的同步超时。另外,我认为一些Unice对于waitpid如何处理信号有不同的规则

评论说他们从Thread.wait中窃取了循环,而threading.py中的评论则表明它用于响应

from subprocess import Popen, PIPE

handle = Popen('ping -n 100 www.google.se', shell=True, stdout=PIPE)
while handle.poll() is None: # <-- Equivilant of .wait()
    print(handle.stdout.readline())
调试时的有用提示:

from subprocess import Popen, PIPE, STDOUT
handle = Popen('ping -n 100 www.google.se', shell=True, stdout=PIPE, stderr=PIPE)
# You need to flush the output buffers:
handle.stderr.readline()
handle.stdout.readline()
# or
handle = Popen('ping -n 100 www.google.se', shell=True, stdout=PIPE, stderr=STDOUT)
handle.stdout.readline() # Does both stdout+stderr at the same time, saves you a line.

# and always close your open filehandles.
handle.stdout.close()
handle.stderr.close() # If you've separated both.
关于您的操作系统问题 我想您可能指的是系统服务或守护进程? 您描述的这些类型的进程被指定为阻塞或非阻塞,这是您要寻找的术语。这些进程的每个init脚本的开发人员确定进程是否应该阻塞,直到完成或达到超时,或者进程是否应该分叉到后台


可能会被阻塞的是OpenLDAP或内部邮件传输程序,而其他进程(如OpenVPN或Apache)可能会被转移到后台,使系统能够继续它的启动顺序。

不必要地运行shell并不能解决总体上的难题,它会造成麻烦,甚至更糟@MikeGraham在8年多的时间里表现强劲,如果你不知道移除它的作用,shell=True会显著减少头痛。因为它将更像任何unixshell的开箱即用。我知道不使用它是很理想的,但是对于新的unix用户来说,像任何其他带有环境变量的unix shell一样运行的默认行为更容易。@根据,我们可以在unix上进行阻塞调用,而不必忙于循环。既然忙着等待进程完成会浪费CPU资源,为什么不在Popen.wait上实现呢?
from subprocess import Popen, PIPE, STDOUT
handle = Popen('ping -n 100 www.google.se', shell=True, stdout=PIPE, stderr=PIPE)
# You need to flush the output buffers:
handle.stderr.readline()
handle.stdout.readline()
# or
handle = Popen('ping -n 100 www.google.se', shell=True, stdout=PIPE, stderr=STDOUT)
handle.stdout.readline() # Does both stdout+stderr at the same time, saves you a line.

# and always close your open filehandles.
handle.stdout.close()
handle.stderr.close() # If you've separated both.