How to lock files (the easiest/best way)?

Carl Banks pavlovevidence at gmail.com
Mon Jul 17 19:46:13 EDT 2006


Carl J. Van Arsdall wrote:
> pavlovevidence at gmail.com wrote:
> >
> > f = open("/path/to/data/directory/lockfile","r")
> > try:
> >     fcntl.flock(f.fileno(),fcntl.LOCK_EX)
> >     ...access data freely here...
> > finally:
> >     f.close()
> >
> > Closing the file should release the lock (unless you have a truly
> > horrible operating system).
> >
> >
> I also find that fcntl has problems with NFS (or at least, *I* had
> problems using the python fcntl module and nfs - could be that horrible
> operating system, but doing things like that over nfs can be tricky).

Ah, that's a tough one.

Apparently, you could lock files on NFS if both the client OS and NFS
server are up to the task (i.e., sufficiently recent), but good luck
getting that to fly.  And, with NFS, even some of the seemingly
foolproof methods like "lock directories" aren't necessarily going to
work.  Cross your fingers and hope you have a solid NFS server and
well-behaved clients.


Carl Banks




More information about the Python-list mailing list