New submission from Stephen Gallagher:

Currently, NamedTemporaryFile takes an attribute at initialization that allows 
it to remove the temporary file on going out of scope or else leave it around. 
However, it's not possible to change this after the fact.

It would be a much more sensible pattern to be able to operate with 
auto-deletion enabled while constructing the file and then to be able to toggle 
this option off once the file is completed.

For example, the use-case I have in mind is that I am creating a file that, 
once complete, will go into a well-known location. Because of known attacks, 
the only secure way to create this file is to generate it in a temporary 
location and then atomically move (os.rename()) it into its final location. 
This avoids time-of-check-time-of-use risks as well as avoiding overwriting the 
old file if something goes wrong.

It would be handy if tempfile could be extended to support this operation.

Additionally, I attempted to solve this by monkey-patching tempfile and 
overriding the __del__ function on the _TemporaryFileWrapper object to be a 
no-op. This works in python 2.7.9, but seems to be ignored on python 3.4.2.

Example code:

{{{
import tempfile
import os

f = tempfile.NamedTemporaryFile()
os.unlink(f.name)
f.unlink = lambda x: None
}}}

If you run that under python2, it will succeed. On Python 3, it will noisily 
report:
Exception ignored in: <bound method _TemporaryFileCloser.__del__ of 
<tempfile._TemporaryFileCloser object at 0x7f7a24548c88>>
Traceback (most recent call last):
  File "/usr/lib64/python3.4/tempfile.py", line 366, in __del__
  File "/usr/lib64/python3.4/tempfile.py", line 362, in close
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpqs5k6w7q'

----------
components: Library (Lib)
messages: 239082
nosy: Stephen Gallagher
priority: normal
severity: normal
status: open
title: tempfile.NamedTemporaryFile should be able to toggle "delete"
versions: Python 2.7, Python 3.4

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue23755>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to