Test if Script Already Running

Marko Rauhamaa marko at pacujo.net
Thu Apr 20 06:32:19 EDT 2017


Jon Ribbens <jon+usenet at unequivocal.eu>:

> On 2017-04-20, Cameron Simpson <cs at zip.com.au> wrote:
>> For myself, I like mkdir. It is portable. It is atomic. It fails if
>> the target exists.  It works over NFS etc. It is easy.
>>
>>   os.mkdir('lock')
>>   ... do stuff ...
>>   os.rmdir('lock')
>
> One downside to this is that if the process that 'holds the lock' dies
> before it reaches the 'rmdir' then the lock becomes wedged. With the
> 'flock' method, the operating system will automatically undo the lock.
> Of course, depending on your application, it's possible that this
> 'downside' may be a feature.

Combining both:

==Begin flock.py========================================================
"""File locking for Linux, Unix and Windows

Usage:

    with FLock(pathname):
        # critical section

where pathname refers to an existing, readable file.

On Windows, FLock creates a magic directory pathname.6e35b8cda6902579
upon locking and removes it upon unlocking. If the operating system
crashes or the Python process is killed ungracefully, the lock directory
could be left behind and would have to be removed manually.
"""

import os

if os.name == 'posix':
    import fcntl

    class FLock:
        def __init__(self, pathname):
            self.f = open(pathname)

        def __enter__(self):
            self.lock()
            return None

        def __exit__(self, exc_type, exc_value, traceback):
            self.unlock()
            return False

        def lock(self):
            fcntl.flock(self.f, fcntl.LOCK_EX)

        def unlock(self):
            self.f.close()

else:
    import time

    class FLock:
        def __init__(self, pathname):
            self.pathname = pathname + ".6e35b8cda6902579"

        def __enter__(self):
            self.lock()
            return None

        def __exit__(self, exc_type, exc_value, traceback):
            self.unlock()
            return False

        def lock(self):
            while True:
                try:
                    os.mkdir(self.pathname)
                    return
                except OSError:
                    time.sleep(1)

        def unlock(self):
            os.rmdir(self.pathname)
==end flock.py==========================================================


Marko


More information about the Python-list mailing list