test if a file is locked?

Carl Banks imbosol at aerojockey.invalid
Mon Dec 22 03:03:38 EST 2003


Benjamin Han wrote:
> 
> 
> On Mon, 22 Dec 2003, Carl Banks wrote:
>> Fortepianissimo wrote:
>> >
>> >
>> > 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.
>> >
>> > 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.
>> >
>> > The reason I need this is I want to serialize parallel processes using
>> > a lock file. Any suggestion is welcome!
>>
>>
>> Try this:
>>
>> fcntl.lockf(f.fileno(),fcntl.LOCK_EX|fcntl.LOCK_NB)
> 
> Ok looks like I'm still missing something: so how do you get 'f' without
> using open() or file()? Either of these will put the script on hold...
> 
> Thanks!

Have you tried it?  (Hint: it's not "open" that waits until the file
is unlocked.)


-- 
CARL BANKS                      http://www.aerojockey.com/software
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work." 
          -- Parody of Mr. T from a Robert Smigel Cartoon




More information about the Python-list mailing list