avoid script running twice

Nick Craig-Wood nick at craig-wood.com
Mon Jun 18 15:30:05 EDT 2007


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)

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list