为什么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)
然后我遇到了一个异常:
IOError: [Errno 24] Too many open files: 'files/file_509'
7 个回答
11
要查看和更改Linux系统上打开文件的限制,可以使用Python的一个模块,叫做 resource:
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))
在Windows上,我按照Punit S的建议做:
import platform
if platform.system() == 'Windows':
import win32file
win32file._setmaxstdio(2048)
15
我在Windows上运行你的代码时也遇到了同样的问题。这个限制是来自C语言的运行时环境。你可以使用win32file来改变这个限制的值:
import win32file
print win32file._getmaxstdio()
上面的代码会让你得到512,这就解释了为什么在#509的时候会失败(加上标准输入、标准错误和标准输出,正如其他人已经提到的那样)
执行以下代码,你的程序就能正常运行了:
win32file._setmaxstdio(2048)
不过要注意,2048是一个硬性限制(底层C标准输入输出的硬性限制)。所以,如果我用大于2048的值来执行_setmaxstdio,就会失败。
43
操作系统对打开的文件数量是有限制的。在Linux系统中,你可以输入
ulimit -n
来查看这个限制是多少。如果你是管理员(root用户),你可以输入
ulimit -n 2048
这样你的程序就可以正常运行了(作为管理员),因为你把打开文件的限制提高到了2048个。