help debug cgi counter?

Fredrik Lundh effbot at telia.com
Mon Sep 11 03:21:55 EDT 2000


Pete wrote:

> the good news, it's working. the bad news, everynow and then "bad
> things" happen. i assume this is because of two instances running
> at the same time (???)

try locking the file during the update:

import fcntl, FCNTL

def runcounter(filename):
    try:
        file = open(filename, 'r+')
        fcntl.flock(file.fileno(), FCNTL.LOCK_EX) # lock
        count = int(file.readline())
        file.seek(0) # rewind
        count = count+1
        file.write(str(count))
        file.close() # release lock
    except:
        count = 1
    return count

(based on fcntl-example-1.py from the eff-bot guide)

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->




More information about the Python-list mailing list