我编写了简单的测试代码,可以在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个打开的文件
要检查 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)
运行代码时,我在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失败.
| 归档时间: |
|
| 查看次数: |
15573 次 |
| 最近记录: |