如何打电话临时文件.mkstemp()带“with”?或者,它为什么不返回一个带有uExit_Uu()的fd?

2024-10-01 09:31:01 发布

您现在位置:Python中文网/ 问答频道 /正文

对我来说,调用tempfile.mkstemp()的最惯用方法是:

with tempfile.mkstemp() as fd, filename:
    pass

然而,这显然是(?)引发AttributeError: __exit__

显式地使用try finally调用os.close(fd)是一种简单的解决方法,但感觉违反了应该有一种——最好只有一种——明显的方法来做到这一点。

有没有一种方法可以在tempfile中“修复”这个问题,或者是否有一个这样实现的基本原理?在


Tags: 方法closeosaswithexitpassfilename
2条回答

with语句的工作方式在PEP 343中定义,包括其所谓的上下文管理协议

This PEP proposes that the protocol consisting of the enter() and exit() methods be known as the "context management protocol", and that objects that implement that protocol be known as "context managers".

mkstemp不返回上下文管理器,上下文管理器是实现__enter__和{}方法的对象,因此不兼容。在

一个明显的解决方法是创建一个实现上下文管理器协议的包装器类。在

tempfile模块中,还有其他更适合创建临时文件的方法,例如^{}等。在

尤其是,如果您不想删除该文件,请使用^{},给它一个delete=False参数。在

相关问题 更多 >