Python: Lock directory

前端 未结 4 499
-上瘾入骨i
-上瘾入骨i 2021-01-19 14:51

AFAIK this code can be used to lock a directory:

class LockDirectory(object):
    def __init__(self, directory):
        assert os.path.exists(directory)
            


        
4条回答
  •  悲&欢浪女
    2021-01-19 15:22

    I change your code a bit,add return self like most context manage do,then with dup(),the second context manage will fail.and the solution is simple,uncommentfcntl.flock(self.dir_fd,fcntl.LOCK_UN)

    The mode used to open the file doesn't matter to flock.

    and you cannot flock on NFS.

    import os
    import fcntl
    import time
    class LockDirectory(object):
        def __init__(self, directory):
            assert os.path.exists(directory)
            self.directory = directory
    
        def __enter__(self):
            self.dir_fd = os.open(self.directory, os.O_RDONLY)
            try:
                fcntl.flock(self.dir_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except IOError as ex:             
                raise Exception('Somebody else is locking %r - quitting.' % self.directory)
            return self
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            # fcntl.flock(self.dir_fd,fcntl.LOCK_UN)
            os.close(self.dir_fd)
    
    def main():
        with LockDirectory("test") as lock:
            newfd = os.dup(lock.dir_fd)
        with LockDirectory("test") as lock2:
            pass
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题