Manix
Manix

Reputation: 93

Python locking and unlocking file from multiple processes

I have a file xxx.txt that is accessed by other Python files. When script_1 is about to write to xxx.txt it should lock the file and script_2 should wait until the file is released by script_1.

I tried using this code but it does not lock the file. script_2 was able to write the file.

import fcntl, os, signal, time


os.fork()

class TimeoutException(Exception): pass

def signal_handler(signum, frame):
    raise TimeoutException()


f = os.open("xxx.txt", os.O_RDWR|os.O_CREAT)
fcntl.flock(f, fcntl.LOCK_EX)
time.sleep(20)
os.write(f, bytes("oook_0", "utf-8"))
fcntl.flock(f, fcntl.LOCK_UN)
os.close(f)

Upvotes: 0

Views: 1213

Answers (2)

Manix
Manix

Reputation: 93

Solved with

from filelock import FileLock

with FileLock("lock"):
    with open('lock', mode='w') as file:
        file.write('oook_1')

Upvotes: 0

Jonathan Gagne
Jonathan Gagne

Reputation: 4379

  1. Ok first, locking a file is a platform-specific operation, so you will need to run different code for different operating systems.
  2. Secondly, as @Kevin said here, - "coordinating access to a single file at the OS level is fraught with all kinds of issues that you probably don't want to solve. Your best bet is have a separate process that coordinates read/write access to that file."

Upvotes: 1

Related Questions