python Popen卡死問題


程序經常卡死,定位了半天才定位到原因,原來是Popen導致的卡死;

程序如下:

s = subprocess.Popen([*,*,*], stdout=subprocess.PIPE)

ret = s.stdout.read()

return ret

官方文檔的解釋是:

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.

原因是使用Popen.wait()后直接讀PIPE.stdout.read()之前,可能緩存已經滿了,此時導致了卡死。

解決辦法:使用communicate()

例如:

s = subprocess.Popen([*,*,*], stdout=subprocess.PIPE)

stdoutdata, stderrdata = s.communicate()

return stdoutdata

此外,最后在調用Popen的時候加上參數close_fds=True,參見官方文檔說明:

popen2 closes all file descriptors by default, but you have to specify close_fds=True with Popen

以后使用Popen還是小心點,這里面坑很多。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM