OSError: [Errno 24] 打开文件太多;在Python中;调试困难

问题描述 投票:0回答:1

我正在运行代码,有时几小时后,有时几分钟后会失败并出现错误

OSError: [Errno 24] Too many open files

我在调试这个问题时遇到了很大的麻烦。错误本身总是由下面代码片段中的标记行触发

try:
    with open(filename, 'rb') as f:
        contents = f.read()       <----- error triggered here
except OSError as e:
    print("e = ", e)
    raise
else:
    # other stuff happens

但是,我在这部分代码中看不到任何问题(对吗?),所以我猜代码的其他部分没有正确关闭文件。然而,虽然我确实经常打开文件,但我总是使用“with”语句打开它们,并且我的理解是,即使发生错误,文件也会被关闭(对吗?)。所以我的代码的另一部分看起来像这样

    try:
        with tarfile.open(filename + '.tar') as tar:
            tar.extractall(path=target_folder)
    except tarfile.ReadError as e:
        print("e = ", e)
    except OSError as e:
        print("e = ", e)
    else:
        # If everything worked, we are done
        return

上面的代码确实经常遇到 ReadError,但即使发生这种情况,文件也应该被关闭,对吗?所以我只是不明白我怎么会遇到太多打开的文件?抱歉,这对您来说是无法重现的,因为我无法对其进行足够的调试,我只是在这里寻找一些提示,因为我迷路了。任何帮助表示感谢...

编辑:我使用的是 MacBook。这是 ulimit -a

的输出
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
file size               (blocks, -f) unlimited
max locked memory       (kbytes, -l) unlimited
max memory size         (kbytes, -m) unlimited
open files                      (-n) 256
pipe size            (512 bytes, -p) 1
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 1418
virtual memory          (kbytes, -v) unlimited

按照@sj95126的建议,我将有关tar文件的代码更改为确保文件关闭的代码

try:
    tar = tarfile.open(filename + '.tar')
    tar.extractall(path=target_folder)
except tarfile.ReadError as e:
    print("tarfile.ReadError e = ", e)
except OSError as e:
    print("e = ", e)
else:
    # If everything worked, we are done
    return
finally:
    print("close tar file")
    try:
        tar.close()
    except:
        print("file already closed")

但是并没有解决问题。

python file-handling with-statement
1个回答
0
投票

unix/linux
系统上,有一个命令可以使用
file locks
检查
open files
的总数或
ulimit -a
限制。在@carl的情况下,输出是:

core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
file size               (blocks, -f) unlimited
max locked memory       (kbytes, -l) unlimited
max memory size         (kbytes, -m) unlimited
open files                      (-n) 256
pipe size            (512 bytes, -p) 1
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 1418
virtual memory          (kbytes, -v) unlimited

如您所见,

open files
file locks
等于
256

open files                      (-n) 256

这是一个非常

small
的价值

@carl 的档案至少包含超过 256 个文件;所以Python使用文件处理程序打开每个文件,然后产生一个

system file lock
(为了在系统上打开文件,你需要一个文件锁,就像指向该文件的指针;要访问数据,可以做任何你想做的事情)

解决方案是将

open files
值设为
unlimited
very big
数字。

根据这个堆栈答案这是如何更改限制

© www.soinside.com 2019 - 2024. All rights reserved.