List all currently open file handles? [duplicate]

半世苍凉 提交于 2019-12-05 08:18:23

The nice way of doing this would be to modify your code to keep track of when it opens a file:

def log_open( *args, **kwargs ):
    print( "Opening a file..." )
    print( *args, **kwargs )
    return open( *args, **kwargs )

Then, use log_open instead of open to open files. You could even do something more hacky, like modifying the File class to log itself. That's covered in the linked question above.

There's probably a disgusting, filthy hack involving the garbage collector or looking in __dict__ or something, but you don't want to do that unless you absolutely really truly seriously must.

lsof, /proc/pid/fd/

If you're using python 2.5+ you can use the with keyword (though 2.5 needs `from future import with_statement)

with open('filename.txt', 'r') as f:
    #do stuff here
    pass
#here f has been closed and disposed properly - even with raised exceptions

I don't know what kind of catastrophic failure needs to bork the with statement, but I assume it's a really bad one. On WinXP, my quick unscientific test:

import time
with open('test.txt', 'w') as f:
   f.write('testing\n')
   while True:
       time.sleep(1)

and then killing the process with Windows Task Manager still wrote the data to file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!