file access

Skip Montanaro skip at pobox.com
Fri Jan 31 08:39:09 EST 2003


    Stefano> I have two or more pyhton scripts running independently. These
    Stefano> script may access the same files to store or retrieve data. As
    Stefano> usual, I would need to avoid any simultaneous access and I can
    Stefano> solve the problem creating some semaphore files.

There are lots of ways to solve this particular problem.  One of the
simplest might be to "lock" the file in question is by using os.open with
the O_CREAT and O_EXCL flags to open a lock file.  You'll probably have to
put it in a loop, something like (untested!):

    import os, time

    def exclopen(fname, mode, timeout=0):
        lockfn = fname + "-lock"
        wait = 0
        while 1:
            try:
                lockfd = os.open(lockfn, os.O_CREAT|os.O_WRONLY|os.O_EXCL)
            except OSError:
                wait += 0.2
                if timeout and wait > timeout:
                    raise IOError, "unable to lock %s within %s seconds" % \
                                   (fname, timeout)
                time.sleep(0.2)
            else:
                os.close(lockfd)
        # at this point we have the lock (created the lock file)
        return open(fname, mode)

    def exclclose(f):
        lockfn = f.name + "-lock"
        f.close()
        # make the original file available again 
        os.unlink(lockfn)

Skip





More information about the Python-list mailing list