2

Possible Duplicate:
Python: single instance of program

I am looking to make a python script be unique in the sense that it can only run once at a time. For example if I run the script and open another session of the same script a second time and the first session is still running, then the second session will just exit and do nothing. Anyone knows how I could implement this?

Community
  • 1
  • 1
Richard
  • 15,152
  • 31
  • 85
  • 111
  • http://stackoverflow.com/questions/380870/python-single-instance-of-program http://stackoverflow.com/questions/220525/ensuring-a-single-instance-of-an-application-in-linux http://stackoverflow.com/questions/1900979/how-to-avoid-multiple-instances-of-a-program – Mark Rushakoff Jun 02 '10 at 16:19
  • Already answered [here](http://stackoverflow.com/questions/380870/python-single-instance-of-program). – RSabet Jun 02 '10 at 16:18

2 Answers2

1

Never written python before, but this is what I've just implemented in mycheckpoint, to prevent it being started twice or more by crond:

import os
import sys
import fcntl
fh=0
def run_once():
    global fh
    fh=open(os.path.realpath(__file__),'r')
    try:
        fcntl.flock(fh,fcntl.LOCK_EX|fcntl.LOCK_NB)
    except:
        os._exit(0)

run_once()
M.D. Klapwijk
  • 313
  • 2
  • 8
0

One poor man's solution is to use a file based lock. If you open a file using os.open(), there is a flag that allows an exclusive lock on the file. See this for reference.

CruiZen
  • 182
  • 2
  • 6