简体   繁体   English

Python打开文件过多(子进程)

[英]Python too many open files (subprocesses)

I seem to be having an issue with Python when I run a script that creates a large number of sub processes. 当我运行创建大量子进程的脚本时,Python似乎出现问题。 The sub process creation code looks similar to: 子流程创建代码类似于:

Code: 码:

def execute(cmd, stdout=None, stderr=subprocess.STDOUT, cwd=None):
    proc = subprocess.Popen(cmd, shell=True, stdout=stdout, stderr=stderr, cwd=cwd)
    atexit.register(lambda: __kill_proc(proc))
    return proc

The error message I am receiving is: 我收到的错误消息是:

OSError: [Errno 24] Too many open files OSError:[Errno 24]打开的文件太多

Once this error occurs, I am unable to create any further sub processes until kill the script and start it again. 一旦发生此错误,我将无法再创建任何子进程,直到杀死脚本并重新启动它。 I am wondering if the following line could be responsible. 我想知道以下行是否可以负责。

atexit.register(lambda: __kill_proc(proc))

Could it be that this line creates a reference to the sub process, resulting in a "file" remaining open until the script exits? 可能是这一行创建了对子进程的引用,导致“文件”保持打开状态,直到脚本退出?

So it seems that the line: 因此,似乎该行:

atexit.register(lambda: __kill_proc(proc))

was indeed the culprit. 的确是罪魁祸首。 This is probably because of the Popen reference being kept around so the process resources aren't free'd. 这可能是因为保留了Popen引用,因此无法释放进程资源。 When I removed that line the error went away. 当我删除该行时,错误消失了。 I have now changed the code as @Bakuriu suggested and am using the process' pid value rather than the Popen instance. 我现在已按照@Bakuriu的建议更改了代码,并使用了进程的pid值而不是Popen实例。

Firstly, run ulimit -a to find out how many the maximum open files are set in your Linux system. 首先,运行ulimit -a找出您的Linux系统中设置了多少个最大打开文件。

Then edit the system configuration file /etc/security/limits.conf and add those code in the bottom. 然后编辑系统配置文件/etc/security/limits.conf并在底部添加这些代码。

* - nofile 204800

Then you can open more sub processes if you want. 然后,您可以根据需要打开更多子流程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM