The problem is anyway well known.
I have two or more pyhton scripts running independently. These script may
access the same files to store or retrieve data. As usual, I would need to
avoid any simultaneous access and I can solve the problem creating some
semaphore files.
I wonder if the python library offers some specific tool to deal with this
problem.
Thanks,
Stefano
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