1#encoding=utf-8 2import os 3import time 4import errno 5 6class FileLockException(Exception): 7 pass 8 9class FileLock(object): 10 """ A file locking mechanism that has context-manager support so 11 you can use it in a with statement. This should be relatively cross 12 compatible as it doesn't rely on msvcrt or fcntl for the locking. 13 """ 14 15 16 def __init__(self, timeout=7200, delay=30): 17 """ Prepare the file locker. Specify the file to lock and optionally 18 the maximum timeout and the delay between each attempt to lock. 19 """ 20 self.is_locked = False 21 self.timeout = timeout 22 self.delay = delay 23 24 def _setLockFileName(self, file_name): 25 self.lockfile = file_name 26 27 def acquire(self): 28 """ Acquire the lock, if possible. If the lock is in use, it check again 29 every `wait` seconds. It does this until it either gets the lock or 30 exceeds `timeout` number of seconds, in which case it throws 31 an exception. 32 """ 33 start_time = time.time() 34 if os.path.isfile(self.lockfile): 35 try: 36 mark_file_mtime = os.path.getmtime(self.lockfile) 37 if (start_time - mark_file_mtime > self.timeout): 38 os.remove(self.lockfile) 39 except Exception as e: 40 print("the lock file is locked by other process") 41 42 while True: 43 try: 44 #open file , other application can't open it 45 self.fd = os.open(self.lockfile, os.O_CREAT|os.O_EXCL|os.O_RDWR) 46 break 47 except OSError as e: 48 if e.errno != errno.EEXIST: 49 raise 50 if (time.time() - start_time) >= self.timeout: 51 raise FileLockException("Timeout occured.") 52 time.sleep(self.delay) 53 self.is_locked = True 54 55 56 def release(self): 57 """ Get rid of the lock by deleting the lockfile. 58 When working in a `with` statement, this gets automatically 59 called at the end. 60 """ 61 # 62 if self.is_locked : 63 os.close(self.fd) 64 os.unlink(self.lockfile) 65 self.is_locked = False 66 67 def lockFile(self, file_name): 68 """ Activated when used in the with statement. 69 Should automatically acquire a lock to be used in the with block. 70 """ 71 self._setLockFileName(file_name) 72 if not self.is_locked: 73 self.acquire() 74 return self 75 76 def releaseFile(self): 77 """ Activated at the end of the with statement. 78 It automatically releases the lock if it isn't locked. 79 """ 80 if self.is_locked: 81 self.release() 82 83 def __del__(self): 84 """ Make sure that the FileLock instance doesn't leave a lockfile 85 lying around. 86 """ 87 self.release() 88 89 90 91#用法比较有意思,使用with关键字。对with关键字来说,FileLock类先执行__enter__函数,然后,执行with块里的那些代码,执行完了之后,再执行__exit__函数,等价于相当于如下形式: 92#try: 93# 执行 __enter__的内容 94# 执行 with_block. 95#finally: 96# 执行 __exit__内容 97#FileLock在__enter__函数独占式创建或打开一个文件,这个文件不会被其他程序或者进程再次创建或者打开,由此形成lock,执行完代码,在__exit__里,关闭并删除文件