2

我有一个对打开文件有强引用的类。如果代码运行时没有任何异常,则文件将正确关闭,因为我在关闭文件的类上显式调用了一个方法。但是,如果随后引发异常,则文件不会正确关闭。

这是我的代码的模拟版本:

class MyFile(object):
    def __init__(self, filename, mode):
        self._handle = open(filename, mode)

    @classmethod
    def open(cls, filename, mode):
        return MyFile(filename, mode)

    def close(self):
        self._handle.close()

    def __del__(self):
        self.close()

    def writerow(data):
        # Special write
        pass

    def __enter__(self):
        return self

    def __exit__(self, *exc_info):
        self.close()

现在,如果我在代码的顶层使用这个类,我将使用 with 语句:

def get_some_dat():
    return 1

with MyFile.open('foo.txt', 'w') as f:
    # do stuff with f
    data = get_some_data()
    f.writerow(data)

但是,MyFile 是由另一个对象间接打开的。我知道大多数 Pythonistas 会说我应该明确关闭文件,但我想确保在对象被销毁时关闭文件。我编写的代码可以解决问题,但我想知道是否有人对实现此行为的更好方法提出建议。

4

1 回答 1

2

这是一个weakref用于确保文件已关闭的示例,即使它是在不使用with ...语法的情况下打开的:

import weakref

class FileHandler:
    def __init__(self, dbf, caller = None):
        if caller is not None:
            self._ref = weakref.ref(caller, self.close)
        self.thefile = open(dbf, 'rb')
    def __enter__(self):
        return self
    def __exit__(self, ext_type, exc_value, traceback):
        self.close()
    def close(self, *args):
        print('closing file')
        self.thefile.close()

class Foo:
    def __init__(self):
        self.fh = FileHandler('/tmp/testfile', caller = self)

def autoclosing_file():
    foo = Foo()

def demo_callback():
    with open('/tmp/testfile', 'w'): pass
    autoclosing_file()


if __name__ == '__main__':
    demo_callback()

印刷

closing file

PS:我怀疑这段代码不是我的,但我已经失去了它来自哪里的任何参考。如果有人知道,请告诉我,以便我可以给出适当的归属。

于 2012-11-12T17:57:22.247 回答