Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

file access

0 views
Skip to first unread message

Stefano Covino

unread,
Jan 31, 2003, 6:20:08 AM1/31/03
to
I apologize for my trivial question. I am still a "pyhton" beginner...

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


Skip Montanaro

unread,
Jan 31, 2003, 8:39:09 AM1/31/03
to

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

0 new messages