Check if a file is available (not used by another process) in Python
开发者_运维百科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.
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
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()).
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.
精彩评论