Checking for duplicate instances of a script...

Joakim Hove hove at bccs.no
Wed Jan 21 13:42:53 CET 2004


"Guillaume Dargaud" <NOusenetSPAM at gdargaud.net> writes:

> Hello, python beginner here,
> How can I make sure that a given script is never run more than once at the
> same time in a system ?

This can probably be done in *many* different ways, maybe there is
even an agreed upon on best solution. This is a small suggestion
based on fcntl.flock() (Unix only I am afraid):

#!/usr/bin/python
import struct, fcntl
import sys
lockfile = "/tmp/.lock"

## Open a file-descriptor for the lock file.
lockH = open(lockfile,"w")

## Try to aquire an exclusive lock on the lock file.
try:
    fcntl.flock(lockH , fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError,e:
    sys.exit("Lockfile %s already locked - an instance is probably already running" % lockfile)


##
## Your code ...
##    


## Release the lock again
fcntl.flock(lockH, fcntl.LOCK_UN)


-- 
  /--------------------------------------------------------------------\
 / Joakim Hove  / hove at bccs.no  /  (55 5) 84076       |                 \
 | Unifob AS, Avdeling for Beregningsvitenskap (BCCS) | Stabburveien 18 |
 | CMU                                                | 5231 Paradis    |
 \ Thormøhlensgt.55, 5020 Bergen.                     | 55 91 28 18     /
  \--------------------------------------------------------------------/



More information about the Python-list mailing list