我最近升级到约塞米蒂。还有一些Python脚本挂在了小牛队上。我的版本是2.7.8。我创建了一个测试用例:
import subprocess
cat = subprocess.Popen(['top', '-l', '1'],
stdout=subprocess.PIPE,
)
cat.wait()
在小牛队比赛,但在约塞米蒂国家公园比赛。当我打断约塞米蒂的话,我看到了以下的回溯。
Traceback (most recent call last):
File "test.py", line 5, in <module>
cat.wait()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1376, in wait
pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 476, in _eintr_retry_call
return func(*args)
KeyboardInterrupt
我做错了什么?
看起来您需要调用communicate()
。来自Python文档:
Popen.wait()
等待子进程终止。设置并返回
returncode
属性。警告:当使用
stdout=PIPE
和/或stderr=PIPE
时,此操作将死锁,并且子进程将向管道生成足够的输出,以便阻止等待OS管道缓冲区接受更多数据。使用communicate()
来避免这种情况。