Proper way to close all files after subprocess Popen and communicate

心已入冬 提交于 2019-12-01 05:53:07

问题


We are having some problems with the dreaded "too many open files" on our Ubuntu Linux machine rrunning a python Twisted application. In many places in our program, we are using subprocess Popen, something like this:

Popen('ifconfig ' + iface, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
output = process.stdout.read()

while in other places we use subprocess communicate:

process = subprocess.Popen(['/usr/bin/env', 'python', self._get_script_path(script_name)],
                       stdin=subprocess.PIPE,
                       stdout=subprocess.PIPE,
                       close_fds=True)
out, err = process.communicate(data)

What exactly do I need to do in both cases in order to close any open file descriptors? Python documentation is not clear on this. From what I gather (which could be wrong) both communicate() and wait() will indeed clean up any open fds on their own. But what about Popen? Do I need to close stdin, stdout, and stderr explicitly after calling Popen if I don't call communicate or wait?


回答1:


According to this source for the subprocess module (link) if you call communicate you should not need to close the stdout and stderr pipes.

Otherwise I would try:

process.stdout.close()
process.stderr.close()

after you are done using the process object.

For instance, when you call .read() directly:

output = process.stdout.read()
process.stdout.close()

Look in the above module source for how communicate() is defined and you'll see that it closes each pipe after it reads from it, so that is what you should also do.




回答2:


If you're using Twisted, don't use subprocess. If you were using spawnProcess instead, you wouldn't need to deal with annoying resource-management problems like this.



来源:https://stackoverflow.com/questions/27451182/proper-way-to-close-all-files-after-subprocess-popen-and-communicate

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