【问题标题】:How to close file descriptors in python?如何在python中关闭文件描述符?
【发布时间】:2016-04-15 12:43:44
【问题描述】:

我在 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 的上下文管理器寻找解决方案。

【问题讨论】:

  • 通常会使用f = open(...); f.close()

标签: python-2.7 file unix stdout


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 2014-03-28
    • 2021-02-20
    • 1970-01-01
    • 2014-04-06
    相关资源
    最近更新 更多