为什么python对文件句柄的数量有限制?

jer*_*boa 20 python

我编写了简单的测试代码,可以在python脚本中打开多少文件:

for i in xrange(2000):
    fp = open('files/file_%d' % i, 'w')
    fp.write(str(i))
    fp.close()

fps = []
for x in xrange(2000):
    h = open('files/file_%d' % x, 'r')
    print h.read()
    fps.append(h)
Run Code Online (Sandbox Code Playgroud)

我得到一个例外

IOError: [Errno 24] Too many open files: 'files/file_509'
Run Code Online (Sandbox Code Playgroud)

Joh*_*ooy 31

打开文件的数量受操作系统的限制.在linux上你可以输入

ulimit -n
Run Code Online (Sandbox Code Playgroud)

看看有什么限制.如果您是root用户,则可以输入

ulimit -n 2048
Run Code Online (Sandbox Code Playgroud)

现在你的程序将运行正常(以root身份),因为你已经将限制提升到2048个打开的文件

  • +1,如果你想使用python代码检查限制,我会添加`import resource; print resource.getrlimit(resource.RLIMIT_NOFILE)`. (11认同)
  • 显然,你不需要 root 来改变它(我刚试过!) (2认同)

Guf*_*ffa 6

很可能是因为操作系统对应用程序可以打开的文件数量有限制.


Fra*_*urt 6

要检查 Linux 上打开文件句柄的更改限制,您可以使用 Python 模块资源

import resource

# the soft limit imposed by the current configuration
# the hard limit imposed by the operating system.
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
print 'Soft limit is ', soft 

# For the following line to run, you need to execute the Python script as root.
resource.setrlimit(resource.RLIMIT_NOFILE, (3000, hard))
Run Code Online (Sandbox Code Playgroud)

在 Windows 上,我按照 Punit S 的建议进行操作:

import platform

if platform.system() == 'Windows':
    import win32file
    win32file._setmaxstdio(2048)
Run Code Online (Sandbox Code Playgroud)


Pun*_*t S 5

运行代码时,我在Windows上看到相同的行为.C运行时存在限制.您可以使用win32file更改限制值:

import win32file

print win32file._getmaxstdio()
Run Code Online (Sandbox Code Playgroud)

以上将给你512,这解释了#509的失败(+ stdin,stderr,stdout,正如其他人已经说过的那样)

执行以下操作,您的代码运行正常:

win32file._setmaxstdio(2048)
Run Code Online (Sandbox Code Playgroud)

请注意,2048是硬限制(但是底层C Stdio的硬限制).因此,对我来说,执行值大于2048的_setmaxstdio失败.

  • 为了完成这项工作,我首先必须进行以下安装:`pip install pywin32` (2认同)