OS independent way to check if a python app is running?

Diez B. Roggisch deets at nospam.web.de
Mon Dec 14 15:48:44 EST 2009


MRAB schrieb:
> python at bdurham.com wrote:
>> Is there an os independent way to check if a python app is running?
>>  
>> Goal: I have a server program based on cherrypy that I only want to 
>> have running once. If a system administrator accidentally attempts to 
>> run this program more than once, I would like the 2nd instance of the 
>> program to detect that its already running and exit.
>>  
> You could use lockfile: http://pypi.python.org/pypi/lockfile/0.7
> 
> If a certain file exists and is locked, then the app is already running.

Not only exists, he should also use the OS' locking mechanisms. The file 
could otherwise be stale.

We use this:


import platform
is_windows = False
if platform.system() == 'Windows':
     is_windows = True
import os


class LockFileCreationException(Exception):
     pass


class LockFile(object):

     def __init__(self, name, fail_on_lock=False, cleanup=True):
         self.name = name
         self.cleanup = cleanup
         try:
             self.fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_APPEND)
         except OSError, e:
             if e[0] == 2:
                 raise LockFileCreationException()
         self.file = os.fdopen(self.fd, "w")
         if is_windows:
             lock_flags = msvcrt.LK_LOCK
         else:
             lock_flags = fcntl.LOCK_EX
         if fail_on_lock:
             if is_windows:
                 lock_flags = msvcrt.LK_NBLCK
             else:
                 lock_flags |= fcntl.LOCK_NB
         try:
             if is_windows:
                 msvcrt.locking(self.file.fileno(), lock_flags, 1)
             else:
                 fcntl.flock(self.file, lock_flags)
         except IOError, e:
             if e[0] == 11:
                 raise LockObtainException()
             raise


     def __enter__(self):
         return self.file


     def __exit__(self, unused_exc_type, unused_exc_val, unused_exc_tb):
         self.file.close()
         # we are told to cleanup after ourselves,
         # however it might be that another process
         # has done so - so we don't fail in that
         # case.
         if self.cleanup:
             try:
                 os.remove(self.name)
             except OSError, e:
                 if not e[0] == 2:
                     raise



Diez



More information about the Python-list mailing list