File locking

Jonathan Giddy jon at
Sat Jun 5 06:49:29 CEST 1999

"A.M. Kuchling" <amk1 at> writes:

>What is the correct solution for doing file locking in Python
>programs?  The docs for the posixfile module say:

After recent experimentation and reading of the source, I discovered that
Python's fcntl.lockf() accepts the flock() arguments, providing a portable 
and useful interface to fcntl locking.

So, the answer is:
fcntl.lockf(fd, FCNTL.LOCK_EX) -- set write (exclusive) lock
fcntl.lockf(fd, FCNTL.LOCK_SH) -- set read (shared) lock
fcntl.lockf(fd, FCNTL.LOCK_UN) -- unlock

with FCNTL.LOCK_NB available for non-blocking lock attempts.

The only trick is that FCNTL doesn't contain these values on all platforms, 
so you need something like:

from FCNTL import *

except NameError:
    LOCK_SH = 1
    LOCK_EX = 2
    LOCK_NB = 4 
    LOCK_UN = 8

More information about the Python-list mailing list