Making sure script only runs once instance at a time.

Sybren Stuvel sybrenUSE at YOURthirdtower.com.imagination
Fri Sep 29 12:25:04 EDT 2006


Tim Williams enlightened us with:
> def check_lock():
>     import os, sys
>     try:
>         os.remove({filename})
>     except:
>         if "Permission denied" in sys.exc_info()[1]:
>             print 'This program is already running'
>             sys.exit()
>     f_lock = open({filename},'w')

Checking for a lock, and later acquiring the lock, seems non-atomic to
me. It's easier to simply create a lock directory. If it fails, the
dir already exists and someone else holds the lock. If it succeeds,
the lock is immediately yours, since you just created the directory.
This is atomic on most OSses AFAIK.

Sybren
-- 
Sybren Stüvel
Stüvel IT - http://www.stuvel.eu/



More information about the Python-list mailing list