title: Python: Lock directory
body: <p>AFAIK this code can be used to lock a directory:</p>
  
  <pre><code>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:
              if ex.errno != errno.EAGAIN:
                  raise
              raise Exception('Somebody else is locking %r - quitting.' % self.directory)
  
      def __exit__(self, exc_type, exc_val, exc_tb):
          self.dir_fd.close()
  </code></pre>
  
  <p>But according to the answers of this question locking a directoy is not possible: <a href="https://stackoverflow.com/questions/52643622/python-lock-a-directory">Python: Lock a directory</a></p>
  
  <p>What is wrong with above code?</p>
  
  <p>I only need to support current linux version. No Windows, Mac or other unix.</p>