avoid script running twice

Jay Loden python at jayloden.com
Mon Jun 18 21:16:42 CEST 2007

Robin Becker wrote:
> I wish to prevent a python script from running twice; it's an hourly job, but 
> can take too long.
> My simplistic script looks like
> .......
> def main():
>      fn = 'MARKER'
>      if os.path.isfile(fn):
>          log('%s: hourly job running already' % formatTime())
>      else:
>          f = open(fn,'w')
>          f.write(str(os.getpid()))
>          f.close()
>          try:
> 	    work()
>          finally:
>              os.remove(fn)
> if __name__=='__main__':
>      main()
> but it occurs to me that I might be killed with prejudice during the long 
> running work(). Is there a smart way to avoid running simultaneously.

You could also write the PID of the currently running process into your MARKER file, rather than just using an empty file. Then if your file exists, you can compare against os.getpid() and decide what to do from there, like killing your existing script, check to see if that PID is still active on the system, etc. 

I've also seen this done by checking the age of the lock file and if it's too old, consider it 'stale' and delete it. 


More information about the Python-list mailing list