Python: module for creating PID-based lockfile?

后端 未结 7 1788
醉酒成梦
醉酒成梦 2020-12-09 03:17

I\'m writing a Python script that may or may not (depending on a bunch of things) run for a long time, and I\'d like to make sure that multiple instances (started via cron)

7条回答
  •  伪装坚强ぢ
    2020-12-09 04:01

    I know this is an old thread, but I also created a simple lock which only relies on python native libraries:

    import fcntl
    import errno
    
    
    class FileLock:
        def __init__(self, filename=None):
            self.filename = os.path.expanduser('~') + '/LOCK_FILE' if filename is None else filename
            self.lock_file = open(self.filename, 'w+')
    
        def unlock(self):
            fcntl.flock(self.lock_file, fcntl.LOCK_UN)
    
        def lock(self, maximum_wait=300):
            waited = 0
            while True:
                try:
                    fcntl.flock(self.lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
                    return True
                except IOError as e:
                    if e.errno != errno.EAGAIN:
                        raise e
                    else:
                        time.sleep(1)
                        waited += 1
                        if waited >= maximum_wait:
                            return False
    

提交回复
热议问题