如何在Linux上用Python检查文件锁?

时间:2018-03-08 18:03:06

标签: python json file locking

我希望有一个模块,其功能包括锁定文件,解锁文件,检查文件是否被锁定,以及使用此锁定功能保存和读取JSON文件的功能。

检查文件是否锁定在常规模块功能中的可行方法是什么?我记得像locking_module.read_lock_status("file.csv")这样的东西。下面是我尝试过的模块代码和两个可以同时运行的脚本,一个写入文件,另一个读取同一个文件。

模块

import fcntl
import json
import time
import struct
import re

def lock(filepath):
    lock_file = open(filepath, "a")
    try:
        fcntl.lockf(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except (OSError, BlockingIOError) as error:
        return error
    return lock_file

def unlock(filepath):
    lock_file = open(filepath, "a")
    try:
        fcntl.lockf(lock_file, fcntl.LOCK_UN)
    except (OSError, BlockingIOError) as error:
        return error
    return lock_file

def read_lock(filepath):
    lock_file = open(filepath, "r")
    lock_data = struct.pack("hhllhh", fcntl.F_WRLCK, 0, 0, 0, 0, 0)
    try:
        lock_query = fcntl.fcntl(lock_file, fcntl.F_GETLK, lock_data)
        lock_status = struct.unpack("hhllhh", lock_query)[0]
    except OSError:
        return False
    return lock_status

def save_JSON(filepath, dictionary, hang_until_unlocked = True):
    if lock(filepath):
        with open(filepath, "w") as file_JSON:
            json.dump(dictionary, file_JSON)
        unlock(filepath)
        return True
    elif hang_until_unlocked:
        while not lock(filepath):
            time.sleep(0.1)
        with open(filepath, "w") as file_JSON:
            json.dump(dictionary, file_JSON)
        unlock(filepath)
        return True
    else:
        return False

def load_JSON(filepath, hang_until_unlocked = True):
    if lock(filepath):
        try:
            with open(filepath) as file_JSON:
                dictionary = json.load(file_JSON)
            unlock(filepath)
            return dictionary
        except:
            return False
    elif hang_until_unlocked:
        while not lock(filepath):
            time.sleep(0.1)
        try:
            with open(filepath) as file_JSON:
                dictionary = json.load(file_JSON)
            unlock(filepath)
            return dictionary
        except:
            return False
    else:
        return False

脚本1

import random

import lock

while True:
    config = {"a": 1, "b": random.randint(1, 2)}
    lock.save_JSON("config.json", config)

脚本2

import lock

while True:
    config = lock.load_JSON("config.json")
    if config:
        print(config)

1 个答案:

答案 0 :(得分:0)

您可以使用子进程从命令行调用lsof,如此

import subprocess
file_lock = str(subprocess.check_output("lsof | grep file_name", shell=True))