Nesting Python context managers
在这个问题中,我定义了一个包含上下文管理器的上下文管理器。 完成此嵌套最简单的正确方法是什么? 我最终在
来自问题的原始代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import itertools as it import tempfile class WriteOnChangeFile: def __init__(self, filename): self.filename = filename def __enter__(self): self.temporary_file = tempfile.TemporaryFile('r+') self.f = self.temporary_file.__enter__() return self.f def __exit__(self, type_, value, traceback): try: try: with open(self.filename, 'r') as real_f: self.f.seek(0) overwrite = any( l != real_l for l, real_l in it.zip_longest(self.f, real_f)) except IOError: overwrite = True if overwrite: with open(self.filename, 'w') as real_f: self.f.seek(0) for l in self.f: real_f.write(l) finally: self.temporary_file.__exit__(type_, value, traceback) |
创建上下文管理器的简单方法是使用
1 2 3 4 5 6 | @contextlib.contextmanager def write_on_change_file(filename): with tempfile.TemporaryFile('r+') as temporary_file: yield temporary_file try: ... some saving logic that you had in __exit__ ... |
然后使用
临时文件将始终正确关闭(当其