【问题标题】:How to call tempfile.mkstemp() with "with"? - or why doesn't it return an fd with __exit__()?如何用“with”调用 tempfile.mkstemp()? - 或者为什么它不返回带有 __exit__() 的 fd?
【发布时间】:2013-08-27 06:28:17
【问题描述】:

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

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

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

使用 try-finally 显式调用 os.close(fd) 是解决此问题的一种简单方法,但感觉违反了应该有一种——最好只有一种——明显的方法。

有没有办法在tempfile 中“修复”这个问题,或者有理由为什么以这种方式实施?

【问题讨论】:

  • 感谢您的反对,请评论如何改进问题。

标签: python with-statement temporary-files python-internals


【解决方案1】:

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

本 PEP 建议由 enter() 组成的协议 和 exit() 方法被称为“上下文管理协议”, 并且实现该协议的对象被称为“上下文 经理”。

mkstemp 不返回上下文管理器,即实现__enter____exit__ 方法的对象,因此不兼容。

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

【讨论】:

    【解决方案2】:

    tempfile 模块中,还有其他更适合创建临时文件的方法,例如TemporaryFile() 等。

    特别是,如果您不想删除文件,请使用NamedTemporaryFile(),并为其提供delete=False 参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 2022-11-02
      相关资源
      最近更新 更多