lock.py 737 B

123456789101112131415161718192021222324252627
  1. import fcntl
  2. from pathlib import Path
  3. lock_file_path = Path(Path('/tmp') / 'lyrebird.lock')
  4. def place_lock():
  5. '''
  6. Places a lockfile file in the user's home directory to prevent
  7. two instances of Lyrebird running at once.
  8. Returns lock file to be closed before application close, if
  9. `None` returned then lock failed and another instance of
  10. Lyrebird is most likely running.
  11. '''
  12. lock_file = open(lock_file_path, 'w')
  13. try:
  14. fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
  15. except:
  16. return None
  17. return lock_file
  18. def destroy_lock():
  19. '''
  20. Destroy the lock file. Should close lock file before running.
  21. '''
  22. if lock_file_path.exists():
  23. lock_file_path.unlink()