Scripts (running once)

Siggy Brentrup bsb at winnegan.de
Mon Jun 25 15:10:06 CEST 2001


Olaf Trygve Berglihn <olafb+usenet at pvv.org> writes:

> mixo <mixo77 at usa.net> writes:
> 
> > How can one find out if there is a particular python script runnig, and
> > hence prevent
> > the same script from being run again? For instance, say I run a script
> > 'mytes.py' with
> > the following command:
> > 
> >             python mytes.py
> > 
> > Now, the next time  a user types the same command, a message saying the
> > script is
> > already running (or something of that sort) should be printed, as the
> > script has not
> > termintated.
> 
> How about using a lock-file? This code removes the lock after the
> program has ended. Replace the finally-statements with a pass if you
> want the program to be executed only once. Note that the user must
> have write-permissons for the lockfile.
> 
> 
> #!/usr/bin/env python
> 
> import os
> 
> LOCKFILE="/tmp/myprog.lock"
> 
> def main():
>         #your code here
>         import time
>         time.sleep(20) # pause for 20 sek.
> 
> if __name__ == '__main__':
>         if os.path.isfile(LOCKFILE):
>                 import sys
>                 sys.stdout.write("Already running myprog\n")
>                 sys.exit(1)
>         else:
>                 fd = open(LOCKFILE, 'w')
>                 fd.close()
>         try:
>                 main()
>         finally:
>                 if os.path.isfile(LOCKFILE):
>                         os.remove(LOCKFILE)

This program contains a raise condition, what if two users are
simultaneously trying to run it.

On *nix systems use instead (Python 2.1):

if __name__ == '__main__':
    from os import O_CREAT, O_EXCL
    import sys
    try:
        fd = os.open(LOCKFILE, O_CREAT+O_EXCL)
    except OSError:
        print >>sys.stderr, 'Already running ...'
        sys.exit(1)
    try:
        main()
    finally:
        os.remove(LOCKFILE)        


-- 
Siggy Brentrup - bsb at winnegan.de - http://www.winnegan.de/
****** ceterum censeo javascriptum esse restrictam *******





More information about the Python-list mailing list