I found this question but I do not know how to use the suggestion. I have tried
with open(fullname) as filein:
fcntl.lockf(filein, fcntl.LOCK_EX | fcntl.LOCK_NB)
and
with open(fullname) as filein:
fcntl.lockf(filein.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
but in both cases I get an error
OSError: [Errno 9] Bad file descriptor
I want to use this method to check if a file is "locked", and ideally to unlock it.
Try to apply the next code snippet:
import fcntl
with open(fullname, 'r') as filein:
try:
fcntl.flock(filein, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print(f"File {fullname} is locked.")
else:
print(f"File {fullname} is locked, but...")
fcntl.flock(filein, fcntl.LOCK_UN)
print("now is not.")