参考:https://py-filelock.readthedocs.io/en/latest/index.html
1. 安装 filelock
python -m pip install filelock
2. 使用文件锁
from filelock import Timeout, FileLock
file_path = "high_ground.txt"
lock_path = "high_ground.txt.lock"
lock = FileLock(lock_path, timeout=1)
with lock:
with open(file_path, "a") as f:
f.write("Hello there!")
lock.acquire()
try:
with open(file_path, "a") as f:
f.write("General Kenobi!")
finally:
lock.release()
@lock
def decorated():
print("You're a decorated Jedi!")
decorated()
包括超时选项的 acquire
try:
with lock.acquire(timeout=10):
with open(file_path, "a") as f:
f.write("I have a bad feeling about this.")
except Timeout:
print("Another instance of this application currently holds the lock.")