列出所有当前打开的文件句柄? [英] List all currently open file handles?

查看:435
本文介绍了列出所有当前打开的文件句柄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
检查在Python中打开了哪些文件

Possible Duplicate:
check what files are open in Python

你好

是否有可能获得所有当前打开的文件句柄的列表,我假设它们存储在环境中的某个位置.

Is it possible to obtain a list of all currently open file handles, I presume that they are stored somewhere in the environment.

我对theis函数感兴趣,因为我希望安全地处理出现致命错误时打开的所有文件,即关闭文件句柄并用原始文件替换可能损坏的文件.

I am interested in theis function as I would like to safely handle any files that are open when a fatal error is raised, i.e. close file handles and replace potentially corrupted files with the original files.

我正在处理,但是不知道打开了哪些文件句柄,所以我无法实现这个想法.

I have the handling working but without knowing what file handles are open, I am unable to implement this idea.

顺便说一句,初始化文件句柄时,可以通过其他导入的方法继承吗?

As an aside, when a file handle is initialised, can this be inherited by another imported method?

谢谢

推荐答案

好的方法是修改代码以跟踪打开文件的时间:

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 )

然后,使用log_open而不是open打开文件.您甚至可以做一些更棘手的事情,例如修改File类以自行记录.上面的链接问题对此进行了介绍.

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.

可能有一个令人作呕的肮脏黑客涉及到垃圾收集器或查看__dict__之类的东西,但是除非您真正非常认真地否则,否则您不想这样做. >必须 .

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.

这篇关于列出所有当前打开的文件句柄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆