avoid script running twice
Tim Williams
tim at tdw.net
Mon Jun 18 15:48:32 EDT 2007
On 18/06/07, Nick Craig-Wood <nick at craig-wood.com> wrote:
> Tim Williams <tim at tdw.net> wrote:
> > You can also do this by holding a file open in write mode until the
> > script has finished.
> >
> > try:
> > open('lock.txt','w')
> > my_script()
> > except:
> > #print script is already running
>
> That only works under windows
>
> >>> f=open('lock.txt','w')
> >>> g=open('lock.txt','w')
> >>> f.write('hi')
> >>> g.write('ho')
> >>> f.close()
> >>> g.close()
> >>> open('lock.txt').read()
> 'ho'
> >>>
>
> The best cross platform way to create a lock is creating a directory.
> It is atomic on both windows and linux anyway.
>
> try:
> os.mkdir("lock")
> except OSError:
> print "locked!"
> else:
> try:
> do_stuff()
> finally:
> os.rmdir("lock")
>
> (untested)
>
Being a windows-only person, I didn't know that :)
Actually I think I did, this thread has happened before - a few months ago :)
I would be worried with the directory-exists option for the same
reason I don't use the file-exists method currently. It is possible
for the directory to exist when the script isn't running, thus
preventing the script from running again until someone notices.
On Windows the open-a-file-for-writing method works well, but as *nix
doesn't work the same way then maybe the socket solution is the best
cross-platform option. The socket can't exist when the script isn't
running, and if you try and create a duplicate socket you catch the
exception and exit.
IMHO of course.
:)
More information about the Python-list
mailing list