Making sure script only runs once instance at a time.

Tim Williams tim at tdw.net
Fri Sep 29 11:26:27 EDT 2006


On 29/09/06, Matthew Warren <Matthew.Warren at digica.com> wrote:
>  I have
> found that in real usage of other programs within the company that use
> lockfiles, it sometimes causes a bit of troubleshooting time when it stops
> working due to a stale lockfile.. This especially happens when the program
> is killed, the lockfile remains and causes minor annoyance (to somebody who
> knows that is, more annoyance to somebody who doesn't).

Then they were checking for the wrong thing :)      Chcking for a lock
file's existance is prone to the above problem.  Checking to see if
anyone "owns" the lock file is better,  and if a running program
doesn't close gracefully it still releases the lock file.

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')

You may want to close the lock file properly during a gracefull shutdown.

HTH :)



More information about the Python-list mailing list