How to use "fcntl.lockf" in Python?

Question:

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.

Asked By: Alex

||

Answers:

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.")
Answered By: Aksen P
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.