Wednesday, March 17, 2010

How to create a temporary file in python

I recently had to write some code to use ssh-keygen to get an SSH key's fingerprint (I wasn't allowed to use any fancy ssh python modules).  ssh-keygen expected the key to be stored in a file, so to get around it I had to create a temporary file.  Here's how you do it in python:

import tempfile
import os

temp_file = tempfile.NamedTemporaryFile()
temp_file.write('hi there')
temp_file.flush()
os.fsync(temp_file.fileno())

print 'Created temporary file "%s"' % (temp_file.name,)

temp_file.close()

Of course, instead of just printing the file name, I used the temporary file to pass to ssh-keygen and extract the key's fingerprint.  Also, always remember to close your file when you're done.  Even if an exception happens, you should close your file handles before leaving so that you don't have files lying around that you don't need.

No comments:

Post a Comment