0

I'm looking for some code to check if a file in the file system is available (not used by another process). How could I do it in Python? Thanks!

How I'll use it: cylically check if file is available and when it is (processes don't need it anymore) delete it.

2
  • 1
    Are Process A and Process B going to use the file, locking it while they do, and Process C is going to poll to see if it can delete the file to know both A & B are done? This is begging to be a race condition - say Process A finishes, releases the file, then C gets timesliced in, deletes the file, then B gets timesliced in and goes to use the file and goes boom. Commented Dec 21, 2010 at 11:04
  • @mtrw It's good point. However in my case it's not so complicated: there's only one process that uses the file and only once. Commented Dec 21, 2010 at 13:04

3 Answers 3

2
while True:
    try:
        os.remove(yourfilename) # try to remove it directly
    except OSError as e:
        if e.errno == errno.ENOENT: # file doesn't exist
            break
        time.sleep(5)
    else:
        break
Sign up to request clarification or add additional context in comments.

1 Comment

+1. A crummy solution to a crummy problem. Of course this assumes the the file is locked/non-deletable. If deletion of the file is meant to mean "the process was done with the file", then, whoops! I wouldn't trust that further than I can jump.
0

If the file other process has the file open and you delete it, it will not be removed from the filesystem until all processes close their handles to it.

If the other process merely needs its file handle/object to continue to work you may safely delete the file, it will be removed when the process closes its handle. If you want to be able to call open() on the file until the process has finished with it, both processes need to use locks (see fcntl.flock()).

Comments

0

Not sure if you are on linux. I think what you are looking is to implement 'fuser' like functionality in python.

If you are on linux, you can iterate through process id's under '/proc' file system and check the files that are being referred by these processes. Check this script fuser.py. You can use the same approach and adapt the code listed above to your needs.

1 Comment

Thanks! Actually I'm working on Windows (unfortunately!) but I hope your answer will help some Linux user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.