如何在python中关闭文件描述符

如何在python中关闭文件描述符

本文介绍了如何在python中关闭文件描述符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有以下代码:

I have the following code in 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

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

it fails at 5100 on OSX with OSError: [Errno 24] Too many open files. I'm wondering why and if there is a solution to close the file descriptor. I'm looking for a solution for a context manager which closes stdout and stderr.

推荐答案

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

I executed your code on a Linux machine and got the same error but at a different number of iterations.I added the following two lines in the __exit__(self, *_) function of your class:

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

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

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

With this change I do not get an error and the script returns successfully. I assume that the duplicated file descriptors stored in self.save_fds are kept open if you don't close them with os.close(fds) and so you get the too many files open error.Anyway my console printed "plop", but maybe this depends on my platform.Let me know if it works :)

这篇关于如何在python中关闭文件描述符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:08