python 文件锁 filelock

创建日期: 2022-08-12 16:33 | 作者: 风波 | 浏览次数: 17 | 分类: Python

参考: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.")
17 浏览
13 爬虫
0 评论