python - Python : generator didn't yield error 中的自定义 'with open()' 语句

标签 python with-statement

我有一个文件类,您可以从中解析数据、写入数据等。我想在任何应用程序中使用它,如下所示:

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__)

上下文管理器是生成器,而不是函数。

关于python - Python : generator didn't yield error 中的自定义 'with open()' 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25445177/

相关文章:

javascript - Jinja2 在 javascript 中访问 dict 列表

python - 启动 Pyramid 应用程序时使用粘贴 "call"方案

python - 使用上下文管理器时对象变为 None

Python 确保 x 是 int,而不是讨厌的 float

python - 蜘蛛 : Cannot close a running event loop

python - 在 python 中实现 T9 字典时输出错误

python - 查找在 : Block 中定义的函数

python - 是否可以让 contextlib.closing() 调用任意清理方法而不是 .close()

python - 如何正确使用 try/except/with 内部函数和 main

Python 使用 BeautifulSoup 抓取图像