问题
I recently upgraded to Yosemite. And some of the Python scripts are hanging that used to run on Mavericks. My version is 2.7.8. I created a test case:
import subprocess
cat = subprocess.Popen(['top', '-l', '1'],
stdout=subprocess.PIPE,
)
cat.wait()
Runs on Maverics but hangs on Yosemite. When I interrupt on Yosemite, I see the following traceback.
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
Any hint as to what am I doing wrong?
回答1:
It looks like you need to call communicate()
. From the Python documentation:
Popen.wait()
Wait for child process to terminate. Set and return
returncode
attribute.Warning: This will deadlock when using
stdout=PIPE
and/orstderr=PIPE
and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that.
来源:https://stackoverflow.com/questions/26854021/python-subprocess-wait-behaves-differently-on-mavericks-and-yosemite