Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use "fcntl.lockf" in Python?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

OSError: [Errno 9] Bad file descriptor

I want to use this method to check if a file is "locked", and ideally to unlock it.

>Solution :

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.")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading