我有一个文件类,您可以从中解析数据、写入数据等。我想在任何应用程序中使用它,如下所示:
f = MyFileClass() # __init__ method puts a lot of default data in object
with f.open() as file: # where f.open() is custom MyFileClass method
file.write("foo") # file should close automatically after this
我试过这个:
# it's in MyFileClass()
from contextlib import contextmanager
@contextmanager
def open(self):
try:
return open(os.path.join(self.directory, self.name), self.flags)
except Exception as e:
print(e.__traceback__)
但是我在运行第一个代码后得到了
第 22 行,在 fill_new_file 中 以 f.open() 作为文件: __enter__ 中的文件“C:\Python34\lib\contextlib.py”,第 61 行 从 None 中引发 RuntimeError("generator didn't yield") RuntimeError:生成器没有产生
我想这不是上下文管理器的工作方式。如何做我想做的事?
请您参考如下方法:
试试这个:
@contextmanager
def open(self):
try:
yield open(os.path.join(self.directory, self.name), self.flags)
except Exception as e:
print(e.__traceback__)
上下文管理器是生成器,而不是函数。
