Making sure script only runs once instance at a time.

Eric S. Johansson esj at harvee.org
Wed Sep 27 13:29:53 EDT 2006


Hari Sekhon wrote:
> I have written a script and I would like to ensure that the script is 
> never run more than once at any given time.
> 
> What is the best way of testing and exiting if there is another version 
> of this script running somewhere on this machine?
> 
> I guess what I'm asking is how to handle system processes the way I can 
> in shell. I am running this on linux.

assuming that you're limiting the script to one running instance of a 
given system, I would recommend searching the list archives for a file 
locking discussion of a few weeks ago.  I had made a post suggesting 
portalocker as simple way to achieve file locks.  Somebody else gave a 
really good discussion of a variety of locking techniques.

the basic technique you want is to use some file as a semaphore, lock 
the file, run your script, and unlock on completion.  choose the right 
locking mechanism, and the lock will go away when the process exits 
which helps on cleanup from abnormal terminations.

---eric




More information about the Python-list mailing list