test if a file is locked?

дамјан г. mk at net.mail.penguinista
Mon Dec 22 12:42:46 CET 2003


> I can lock a file using the following snippet:
> 
> ---
> import fcntl
> 
> f=open('flock.txt','w')
> fcntl.lockf(f.fileno(),fcntl.LOCK_EX)
> ---
> 
> If some other script tries to open 'flock.txt', it'll wait until the
> file is unlocked/closed.

This is not true on my system (Linux-2.4.23/glibc-2.3.2), after locking the
file Ican still open it with another script or program (like "cat").

The other script blocks only when I try to lock the file again.

> My question is, I'd like to tell a script to quit *immediately* if it
> cannot open the file, or, if it knows the file is locked.

try this:
        fcntl.lockf(f.fileno(),fcntl.LOCK_EX|fcntl.LOCK_NB)
it will throw an exception if the file is locked:
        IOError: [Errno 11] Resource temporarily unavailable



-- 
Дамјан                                  (jabberID:damjan at bagra.net.mk)

           Intel: where Quality is job number 0.9998782345!




More information about the Python-list mailing list