Python subprocess wait() behaves differently on mavericks and Yosemite

谁说胖子不能爱 提交于 2020-01-14 19:30:33

问题


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/or stderr=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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!