创建文件后可以更改 NamedTemporaryFile 的删除标志吗?

发布于 2024-12-15 15:16:36 字数 106 浏览 0 评论 0原文

创建此类文件后,如何更改 NamedTemporaryFile 的删除标志?

为什么?虽然大多数时候我不需要保留临时文件,但如果我从代码内部检测到错误,我想保留它们以便能够分析它们。

How can I change the delete flag from a NamedTemporaryFile after the creation of such file?

Why? While most of the time I don't need to keep temporary files, if I detect an error from inside the code I want to keep them in order to be able to analyse them.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

懒猫 2024-12-22 15:16:36

对于现在在谷歌上搜索这个问题的人来说,至少对于 Python 3+ 而言,在实例化 NamedTemporaryFile 后更改 delete 不会改变其初始行为,因为实际的标志存储在一个名为_closer (这是一个 _TemporaryFileCloser 实例)。请参阅 Python 中的 tempfile.py,作为官方 Python 文档 不要提及任何事情。

因此,您要么更改此未记录属性:

f = tempfile.NamedTemporaryFile(delete=True)
# f.delete = False  # This doesn't change anything
f._closer.delete = False  # undocumented
f.close()  # the file won't be deleted

或者始终使用NamedTemporaryFile(delete=False)创建,然后如果您不再需要该文件,则手动删除该文件。

For anybody now googling this question, at least for Python 3+, changing delete after instantiating NamedTemporaryFile does not change its initial behaviour, because the actual flag is stored in a object called _closer (which is a _TemporaryFileCloser instance). See tempfile.py in Python, as the official Python docs don't mention anything.

So you either change this undocumented attribute:

f = tempfile.NamedTemporaryFile(delete=True)
# f.delete = False  # This doesn't change anything
f._closer.delete = False  # undocumented
f.close()  # the file won't be deleted

Or you always create with NamedTemporaryFile(delete=False), and then delete the file manually if you don't want the file anymore.

×纯※雪 2024-12-22 15:16:36

根据源代码,delete 只是存储为 NamedTemporaryFile 返回的对象的一个​​属性,因此您可以在关闭它之前进行任意修改。

f = NamedTemporaryFile()
# stuff
f.delete = False
f.close()

编辑:这对于 Python 2 来说是正确的;对于 Python 3,请参阅 Augusto Men 的回答。

According to the source code, delete is just stored as an attribute of the object returned by NamedTemporaryFile, so you can modify as much as you want before closing it.

f = NamedTemporaryFile()
# stuff
f.delete = False
f.close()

EDIT : this is true for Python 2 ; for Python 3, see Augusto Men's answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文