2024-10-01 09:31:01 发布
网友
对我来说,调用tempfile.mkstemp()的最惯用方法是:
tempfile.mkstemp()
with tempfile.mkstemp() as fd, filename: pass
然而,这显然是(?)引发AttributeError: __exit__
AttributeError: __exit__
显式地使用try finally调用os.close(fd)是一种简单的解决方法,但感觉违反了应该有一种——最好只有一种——明显的方法来做到这一点。
os.close(fd)
有没有一种方法可以在tempfile中“修复”这个问题,或者是否有一个这样实现的基本原理?在
tempfile
with语句的工作方式在PEP 343中定义,包括其所谓的上下文管理协议:
with
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__和{}方法的对象,因此不兼容。在
mkstemp
__enter__
一个明显的解决方法是创建一个实现上下文管理器协议的包装器类。在
在tempfile模块中,还有其他更适合创建临时文件的方法,例如^{}等。在
尤其是,如果您不想删除该文件,请使用^{},给它一个delete=False参数。在
delete=False
with
语句的工作方式在PEP 343中定义,包括其所谓的上下文管理协议:mkstemp
不返回上下文管理器,上下文管理器是实现__enter__
和{一个明显的解决方法是创建一个实现上下文管理器协议的包装器类。在
在} 等。在
tempfile
模块中,还有其他更适合创建临时文件的方法,例如^{尤其是,如果您不想删除该文件,请使用^{} ,给它一个
delete=False
参数。在相关问题 更多 >
编程相关推荐