test if a file is locked?

Benjamin Han bhan at andrew.cmu.edu
Mon Dec 22 02:50:19 EST 2003


On Mon, 22 Dec 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...

I got it, thanks!




More information about the Python-list mailing list