Add a lock--fcntl module to a file in Python
Import Fcntl
Open a file
# #当前目录下test文件要先存在, if not present will error. or open it in a written way.
f = open ('./test ')
Encrypt the file:
Fcntl.flock (F,fcntl. LOCK_EX)
This locks the file test, and if there are other processes that lock the test file, it cannot be successful and will be blocked, but will not exit the program.
Unlock: Fcntl.flock (f,fcntl. Lock_un)
FCNTL module:
Flock (): Flock (f, operation)
Operation: including:
Fcntl. Lock_un Unlocking
Fcntl. LOCK_EX Exclusive Lock
Fcntl. Lock_sh shared Lock
Fcntl. LOCK_NB non-blocking lock
Lock_sh shared Lock: All processes do not have write access, even if the lock process is not. All processes have read access rights.
LOCK_EX Exclusive Lock: Other processes other than the lock process do not have read and write access to the locked file.
LOCK_NB non-blocking lock:
If this parameter is specified, the function does not get a file lock and returns immediately, otherwise the function waits for a file lock.
LOCK_NB can perform a bitwise OR (|) operation with the Lock_sh or LOCK_NB. Fcnt.flock (F,fcntl. Lock_ex|fcntl. LOCK_NB)
See examples:
1 Import sys 2 import time 3 import fcntl 4 5 class FLOCK (object): 6 7 def __init__ (self, name): 8 Self.fo BJ = open (name, ' W ') 9 self.fd = Self.fobj.fileno () def Lock (self): try:13 fcntl.lockf (SELF.FD, Fcntl. LOCK_EX | Fcntl. LOCK_NB) # Lock the file and use the FCNTL. Lock_nb14 print ' Lock the file, wait ... ' time.sleep ( +) True17 except:18 print ' File lock, cannot be executed, please run later. ' return False20 def unlock (self): self.fobj.close () print ' unlocked ' if __name__ = = ' __main__ ": print sys.argv[1]28 locker = FLOCK (sys.argv[1]) a = Locker.lock () if a:31 print ' File is locked ' else:33 print ' cannot execute, program is locked, please wait '
Running a terminal first will print:
Python lockfile.py test
Test
Lock the file, wait ...
File is locked
To run a different terminal:
Test
File is locked and cannot be executed, please run it later.
Cannot execute, program is locked, please wait
interprocess communication in Python-the use of the Fcntl module for file locks