Python子进程耗尽文件描述符

Spe*_*bun 6 python garbage-collection file-descriptor

我有一个长期运行的python项目,它使用子进程模块启动各种其他程序.它等待每个程序完成,然后结束包装函数并返回其等待循环.

最终,这使得它运行的计算机停止运行,错误是没有更多的文件描述符可用.

我无法在子流程文档中的任何地方找到子进程关闭时文件描述符会发生什么.起初,我以为它们会自动关闭,因为subprocess.call()命令会一直等到子节点终止.

但如果是这样的话我就不会有问题了.我还认为如果还有剩下的东西,python会在函数完成时进行垃圾收集,并且文件描述符超出范围.但这似乎也不是这样.

我如何才能访问这些文件描述符?subprocess.call()函数只返回退出代码,而不是打开文件描述符.还有什么我在这里不见了吗?

该项目充当各种企业应用程序之间的粘合剂.所述应用程序不能流水线化,它们是gui系统.所以,我唯一能做的就是用内置宏启动它们.这些宏输出文本文件,我用它来管道中的下一个程序.

是的,它听起来一样糟糕.幸运的是,所有文件最终都有非常独特的名字.因此,在接下来的几天里,我将使用下面建议的sys internals工具来尝试跟踪文件.我会告诉你结果如何.

我打开的大多数文件,我只是使用win32file.CopyFile()函数移动它们.

小智 5

我有同样的问题。

我们经常使用 subprocess.Popen() 在 Windows 环境中调用外部工具。在某些时候,我们遇到了没有更多文件描述符可用的问题。我们深入研究了这个问题,发现 subprocess.Popen 实例在 Windows 中的行为与在 Linux 中不同。

如果 Popen 实例没有被销毁(例如通过某种方式保持引用,从而不允许垃圾收集器销毁对象),在调用期间创建的管道在 Windows 中保持打开状态,而在 Linux 中它们在 Popen 后自动关闭.communicate() 被调用。如果在进一步的调用中继续这样做,来自管道的“僵尸”文件描述符将堆积起来,最终导致 Python 异常IOError: [Errno 24] Too many open files

如何在 Python 中获取打开的文件描述符

为了解决我们的问题,我们需要一种方法来在 Python 脚本中获取有效的文件描述符。因此,我们制作了以下脚本。请注意,我们只检查从 0 到 100 的文件描述符,因为我们不会同时打开这么多文件。

fd_table_status.py :

import os
import stat

_fd_types = (
    ('REG', stat.S_ISREG),
    ('FIFO', stat.S_ISFIFO),
    ('DIR', stat.S_ISDIR),
    ('CHR', stat.S_ISCHR),
    ('BLK', stat.S_ISBLK),
    ('LNK', stat.S_ISLNK),
    ('SOCK', stat.S_ISSOCK)
)

def fd_table_status():
    result = []
    for fd in range(100):
        try:
            s = os.fstat(fd)
        except:
            continue
        for fd_type, func in _fd_types:
            if func(s.st_mode):
                break
        else:
            fd_type = str(s.st_mode)
        result.append((fd, fd_type))
    return result

def fd_table_status_logify(fd_table_result):
    return ('Open file handles: ' +
            ', '.join(['{0}: {1}'.format(*i) for i in fd_table_result]))

def fd_table_status_str():
    return fd_table_status_logify(fd_table_status())

if __name__=='__main__':
    print fd_table_status_str()
Run Code Online (Sandbox Code Playgroud)

简单运行时,它将显示所有打开的文件描述符及其各自的类型:

$> python fd_table_status.py
Open file handles: 0: CHR, 1: CHR, 2: CHR
$>
Run Code Online (Sandbox Code Playgroud)

通过 Python 代码调用 fd_table_status_str() 的输出是一样的。有关“CHR”和尊重“短代码”含义的详细信息,请参阅有关 stat 的 Python 文档

测试文件描述符行为

尝试在 Linux 和 Windows 中运行以下脚本:

test_fd_handling.py :

import fd_table_status
import subprocess
import platform

fds = fd_table_status.fd_table_status_str

if platform.system()=='Windows':
    python_exe = r'C:\Python27\python.exe'
else:
    python_exe = 'python'

print '1) Initial file descriptors:\n' + fds()
f = open('fd_table_status.py', 'r')
print '2) After file open, before Popen:\n' + fds()
p = subprocess.Popen(['python', 'fd_table_status.py'],
                     stdin=subprocess.PIPE,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)
print '3) After Popen, before reading piped output:\n' + fds()
result = p.communicate()
print '4) After Popen.communicate():\n' + fds()
del p
print '5) After deleting reference to Popen instance:\n' + fds()
del f
print '6) After deleting reference to file instance:\n' + fds()
print '7) child process had the following file descriptors:'
print result[0][:-1]
Run Code Online (Sandbox Code Playgroud)

Linux 输出

1) Initial file descriptors:
Open file handles: 0: CHR, 1: CHR, 2: CHR
2) After file open, before Popen:
Open file handles: 0: CHR, 1: CHR, 2: CHR, 3: REG
3) After Popen, before reading piped output:
Open file handles: 0: CHR, 1: CHR, 2: CHR, 3: REG, 5: FIFO, 6: FIFO, 8: FIFO
4) After Popen.communicate():
Open file handles: 0: CHR, 1: CHR, 2: CHR, 3: REG
5) After deleting reference to Popen instance:
Open file handles: 0: CHR, 1: CHR, 2: CHR, 3: REG
6) After deleting reference to file instance:
Open file handles: 0: CHR, 1: CHR, 2: CHR
7) child process had the following file descriptors:
Open file handles: 0: FIFO, 1: FIFO, 2: FIFO, 3: REG
Run Code Online (Sandbox Code Playgroud)

窗口输出

1) Initial file descriptors:
Open file handles: 0: CHR, 1: CHR, 2: CHR
2) After file open, before Popen:
Open file handles: 0: CHR, 1: CHR, 2: CHR, 3: REG
3) After Popen, before reading piped output:
Open file handles: 0: CHR, 1: CHR, 2: CHR, 3: REG, 4: FIFO, 5: FIFO, 6: FIFO
4) After Popen.communicate():
Open file handles: 0: CHR, 1: CHR, 2: CHR, 3: REG, 5: FIFO, 6: FIFO
5) After deleting reference to Popen instance:
Open file handles: 0: CHR, 1: CHR, 2: CHR, 3: REG
6) After deleting reference to file instance:
Open file handles: 0: CHR, 1: CHR, 2: CHR
7) child process had the following file descriptors:
Open file handles: 0: FIFO, 1: FIFO, 2: FIFO
Run Code Online (Sandbox Code Playgroud)

正如您在第 4 步中看到的,Windows 的行为与 Linux 不同。必须销毁 Popen 实例才能关闭管道。

顺便说一句,第 7 步中的差异显示了有关 Windows 中 Python 解释器行为的不同问题,您可以在此处查看有关这两个问题的更多详细信息。