[python-win32] Re: How to implement a file lock ??

Miki Tebeka miki.tebeka at zoran.com
Tue Feb 15 10:56:06 CET 2005


Hello ionel,

> is there a cross-platform library or module for file locking?
> or at least a win32 implementation.
> 
> i'm trying to get a lock on some file in a cgi script. ( i got my data
> erased a few times :P )

I'm using:

---------
from os import open as _open, O_CREAT, O_EXCL, O_RDWR

lockfile = "/tmp/some_lock"
lockfd = None

def lock():
    global lockfd
    try:
        lockfd = _open(lockfile, O_CREAT|O_EXCL|O_RDWR)
        write(lockfd, "%d" % getpid())
        return 1
    except OSError: # Already locked
        lockfd = None
        return 0

def unlock():
    if not lockfd:
        return 0
    try:
        close(lockfd)
        remove(lockfile)
        return 1
    except OSError:
        return 0
---------

You can wrap it in a class. However make sure you unlock either on __del__
with is a bit tricky or atexit.register(unlock) which is better.

HTH.
--
------------------------------------------------------------------------
Miki Tebeka <miki.tebeka at zoran.com>
http://tebeka.bizhat.com
The only difference between children and adults is the price of the toys


More information about the Python-win32 mailing list