This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Stephen Gallagher
Recipients Stephen Gallagher
Date 2015-03-24.00:55:05
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1427158506.1.0.856842662258.issue23755@psf.upfronthosting.co.za>
In-reply-to
Content
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'
History
Date User Action Args
2015-03-24 00:55:06Stephen Gallaghersetrecipients: + Stephen Gallagher
2015-03-24 00:55:06Stephen Gallaghersetmessageid: <1427158506.1.0.856842662258.issue23755@psf.upfronthosting.co.za>
2015-03-24 00:55:06Stephen Gallagherlinkissue23755 messages
2015-03-24 00:55:05Stephen Gallaghercreate