fcntl Python's standard library

 

 

In the linux environment using Python project development process often encounter multiple processes to read and write to the same file problem, and then we should lock the file control, there may fcntl module under linux version of Python easy to add files, unlock control.

import fcntl
file_path = "/home/ubuntu/aaa.json"
f = open(file_path, 'w')
fcntl.flock(f.fileno(), fcntl.LOCK_EX)	# 加锁,其它进程对文件操作则不能成功
f.write("something")
fcntl.flock(f.fileno(), fcntl.LOCK_UN)	# 解锁
f.close()

fcntl.flock (f.fileno (), operation) operation comprised of the following options:

  • fcntl.LOCK_EX

    Exclusive lock: In addition to locking other processes do not read and write access to the file has been locked

  • fcntl.LOCK_UN

    Unlock: lock the file to be unlocked

  • fcntl.LOCK_SH

    Shared locks: all processes have no write permissions , even if the process did not lock, but all the process has read permission

  • fcntl.LOCK_NB

    Non-blocking lock: If specified, the function returns a file lock can not be obtained immediately. Otherwise, the function will wait to obtain a lock file.

    LOCK_NB may be the same or bitwise or LOCK_SH LOCK_NB (|) arithmetic operation.

    fcnt.flock(f.fileno(),fcntl.LOCK_EX|fcntl.LOCK_NB)
 

Guess you like

Origin www.cnblogs.com/taosiyu/p/12040354.html