SimpleDao

使用文件锁,支持linux和windows

  1. import os
  2. import sys
  3. import time
  4. import logging
  5. logger = logging
  6. class SingleInstance:
  7. def __init__(self):
  8. py_file_path = os.path.abspath(__file__)
  9. basepath = os.path.dirname(py_file_path)
  10. self.lockfile = os.path.normpath(basepath + '/' + os.path.basename(__file__) + '.lock')
  11. if sys.platform == 'win32':
  12. try:
  13. # file already exists, we try to remove (in case previous execution was interrupted)
  14. if os.path.exists(self.lockfile):
  15. os.unlink(self.lockfile)
  16. self.fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR)
  17. except OSError as e:
  18. if e.errno == 13:
  19. logger.error("Another instance is already running, quit.")
  20. sys.exit(-1)
  21. raise e
  22. else:
  23. # non Windows
  24. import fcntl
  25. self.fp = open(self.lockfile, 'w')
  26. try:
  27. fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
  28. except IOError:
  29. logger.error("Another instance is already running, quit.")
  30. sys.exit(-1)
  31. if __name__ == '__main__':
  32. instance = SingleInstance()
  33. time.sleep(10)