Scripts (running once)

Olaf Trygve Berglihn olafb+usenet at pvv.org
Mon Jun 25 08:28:59 EDT 2001


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)
-- 
Olaf Trygve Berglihn <olafb+usenet at pvv.org>



More information about the Python-list mailing list