How to safely maintain a status file

Richard Baron Penman richardbp at gmail.com
Sun Jul 8 07:29:41 EDT 2012


Hello,

I want my script to generate a ~1KB status file several times a second.
The script may be terminated at any time but the status file must not
be corrupted.
When the script is started next time the status file will be read to
check what needs to be done.

My initial solution was a thread that writes status to a tmp file
first and then renames:

open(tmp_file, 'w').write(status)
os.rename(tmp_file, status_file)

This works well on Linux but Windows raises an error when status_file
already exists.
http://docs.python.org/library/os.html#os.rename


I guess I could delete the status file:

open(tmp_file, 'w').write(status)
if os.path.exists(status_file):
    os.remove(status_file)
os.rename(tmp_file, status_file)

and then on startup read from tmp_file if status_file does not exist.
But this seems awkward.


Is there a better way? Or do I need to use a database?

Richard



More information about the Python-list mailing list