See another answer and comments on how many files open in Python. If you read all this and want to block access to the file on the POSIX platform, you can use the fcntl library.
Keep in mind that: A) other programs can ignore your lock in the file, B) some network file systems do not lock very well or generally C) be very careful to release locks and avoid deadlock as flock will not detect it [1 ] [2] .
Example .... script_a.py
from datetime import datetime from time import sleep import fcntl while True: sleep(1) with open('foo.txt', 'w') as f: s = str(datetime.now()) print datetime.now(), "Waiting for lock" fcntl.flock(f, fcntl.LOCK_EX) print datetime.now(), "Lock clear, writing" sleep(3) f.write(s) print datetime.now(), "releasing lock" fcntl.flock(f, fcntl.LOCK_UN)
script_b.py
import fcntl from datetime import datetime while True: with open('foo.txt') as f: print datetime.now(), "Getting lock" fcntl.flock(f, fcntl.LOCK_EX) print datetime.now(), "Got lock, reading file" s = f.read() print datetime.now(), "Read file, releasing lock" fcntl.flock(f, fcntl.LOCK_UN) print s
Hope this helps!
mdadm source share