Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #25042 > unrolled thread

How to safely maintain a status file

Started byRichard Baron Penman <richardbp@gmail.com>
First post2012-07-08 21:29 +1000
Last post2012-07-09 14:02 +0000
Articles 2 — 2 participants

Back to article view | Back to comp.lang.python


Contents

  How to safely maintain a status file Richard Baron Penman <richardbp@gmail.com> - 2012-07-08 21:29 +1000
    Re: How to safely maintain a status file Duncan Booth <duncan.booth@invalid.invalid> - 2012-07-09 14:02 +0000

#25042 — How to safely maintain a status file

FromRichard Baron Penman <richardbp@gmail.com>
Date2012-07-08 21:29 +1000
SubjectHow to safely maintain a status file
Message-ID<mailman.1916.1341747003.4697.python-list@python.org>
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

[toc] | [next] | [standalone]


#25084

FromDuncan Booth <duncan.booth@invalid.invalid>
Date2012-07-09 14:02 +0000
Message-ID<XnsA08B98A8ACFF1duncanbooth@127.0.0.1>
In reply to#25042
Richard Baron Penman <richardbp@gmail.com> wrote:

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

Using a database would seem to meet a lot of your needs. Don't forget that 
Python comes with a sqlite database engine included, so it shouldn't take 
you more than a few lines of code to open the database once and then write 
out your status every few seconds.

import sqlite3

con = sqlite3.connect('status.db')

...
with con:
    cur = con.cursor()
    cur.execute('UPDATE ...', ...)

and similar code to restore the status or create required tables on 
startup.

-- 
Duncan Booth http://kupuguy.blogspot.com

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web