如何关闭 python 中的文件描述符?

How to close file descriptors in python?

我在python中有以下代码:

import os


class suppress_stdout_stderr(object):
    '''
    A context manager for doing a "deep suppression" of stdout and stderr in
    Python, i.e. will suppress all print, even if the print originates in a
    compiled C/Fortran sub-function.
       This will not suppress raised exceptions, since exceptions are printed
    to stderr just before a script exits, and after the context manager has
    exited (at least, I think that is why it lets exceptions through).

    '''
    def __init__(self):
        # Open a pair of null files
        self.null_fds = [os.open(os.devnull,os.O_RDWR) for x in range(2)]
        # Save the actual stdout (1) and stderr (2) file descriptors.
        self.save_fds = (os.dup(1), os.dup(2))

    def __enter__(self):
        # Assign the null pointers to stdout and stderr.
        os.dup2(self.null_fds[0],1)
        os.dup2(self.null_fds[1],2)

    def __exit__(self, *_):
        # Re-assign the real stdout/stderr back to (1) and (2)
        os.dup2(self.save_fds[0],1)
        os.dup2(self.save_fds[1],2)
        # Close the null files
        os.close(self.null_fds[0])
        os.close(self.null_fds[1])

for i in range(10**6):
    with suppress_stdout_stderr():
        print 'plop'
    if i % 50 == 0:
        print i

它在 OSX 的 5100 处失败,OSError: [Errno 24] Too many open files。我想知道为什么以及是否有关闭文件描述符的解决方案。我正在寻找关闭 stdout 和 stderr 的上下文管理器的解决方案。

我在 Linux 机器上执行了你的代码,得到了同样的错误,但迭代次数不同。 我在 class 的 __exit__(self, *_) 函数中添加了以下两行:

os.close(self.save_fds[0]) os.close(self.save_fds[1])

通过此更改,我没有收到错误并且脚本 returns 成功。我假设如果您不使用 os.close(fds) 关闭存储在 self.save_fds 中的重复文件描述符,它们将保持打开状态,因此您会收到太多文件打开错误。 不管怎样,我的控制台打印了 "plop",但这可能取决于我的平台。 让我知道它是否有效:)