monkeypatching NamedTemporaryFile

J

Jason Lunz

Is there a better way to do this?

def QuietNamedTemporaryFile(**kwargs):

'''
Return a NamedTemporaryFile that doesn't complain when its file has already
been unlinked at __del__ time.
'''

tf = tempfile.NamedTemporaryFile(**kwargs)

def quiet_del():
try:
tf.close()
except OSError:
pass

tf.__del__ = quiet_del

return tf

Jason
 
C

craighse888

Maybe that should be the default behaviour. Presumably the file has
been deleted by some other process?
 
J

Jason Lunz

(e-mail address removed) said:
Maybe that should be the default behaviour. Presumably the file has
been deleted by some other process?

The use case is that a NamedTemporaryFile was used to securely create
and populate a file, which is then atomically (on posix) os.rename()d to
its final location.

If any error occurs prior to the rename, NamedTemporaryFile takes care
of deleting the tempfile on the error path. But in the success case,
NamedTemporaryFile causes an unsightly "ignored exception" message on
stderr when it fails to unlink the now-nonexistent tempfile.

Jason
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top