Python 实践:文件锁
    
      
        
        2021.12.03
      
      
        
          
          Niyao
        
      
      
      
      
       
        
            热度 
           ℃
        
      
      
    
  
  
    
      | import fcntlclass FileLock(object):
 def __init__(self, file_name):
 self.file_name = file_name
 self.handle = open(file_name, 'a+')
 
 def lock(self):
 try:
 fcntl.flock(self.handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
 return True
 except Exception as e:
 print(e)
 return False
 
 def unlock(self):
 fcntl.flock(self.handle, fcntl.LOCK_UN)
 
 
 def __del__(self):
 try:
 self.handle.close()
 except Exception as e:
 print(e)
 pass
 
 |