自動建立pid檔案,並加鎖

G8bao7發表於2015-10-26


點選(此處)摺疊或開啟

  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. import sys
  4. import os
  5. import re
  6. import traceback
  7. import fcntl

  8. class PidFile():
  9.     def __init__(self, file = None):
  10.         if file == None:
  11.             argv0_list = sys.argv[0].split("\\")
  12.             scname = argv0_list[len(argv0_list) - 1]
  13.             if re.search(".py$", scname):
  14.             scname = scname[0:-3]
  15.             self.file = "/tmp/%s.pid" % (scname)
  16.         else:
  17.             self.file = file
  18.         self.pidfile = None

  19.     def _create(self, file):
  20.         f = open(file, "w")
  21.         pid = os.getpid()
  22.         f.write("%s" % (pid))
  23.         f.close()

  24.     def __enter__(self):
  25.         if not os.path.isfile(self.file):
  26.             self._create(self.file)
  27.         self.pidfile = open(self.file, 'a+')
  28.         try:
  29.             fcntl.flock(self.pidfile.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
  30.             return True
  31.         except:
  32.             traceback.print_exc()
  33.             fpid = open(self.file, "r").read()
  34.             raise SystemExit("Process id %s Already running , pid to %s " % (fpid, self.file))
  35.         return False    

  36.     def __exit__(self, *args):
  37.         try:
  38.             self.pidfile.close()
  39.         except :
  40.             pass
  41.         os.remove(self.file)


  42. if __name__ == "__main__":
  43.     # use
  44.     with PidFile() as t:
  45.         print "lock file %s" % (file)
  46.         time.sleep(10)
  47.     exit(0)

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/26250550/viewspace-1816377/,如需轉載,請註明出處,否則將追究法律責任。

相關文章