列出所有当前打开的文件句柄?
可能的重复:
检查 Python 中打开了哪些文件
您好,
是否可以获得所有当前打开的文件句柄的列表,我认为它们存储在环境中的某个位置。
我对这个函数感兴趣,因为我想安全地处理出现致命错误时打开的任何文件,即关闭文件句柄并用原始文件替换可能损坏的文件。
我可以进行处理,但不知道打开了哪些文件句柄,我无法实现这个想法。
顺便说一句,当初始化文件句柄时,它可以被另一个导入的方法继承吗?
谢谢
Possible Duplicate:
check what files are open in Python
Hello,
Is it possible to obtain a list of all currently open file handles, I presume that they are stored somewhere in the environment.
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?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
lsof,/proc/pid/fd/
lsof, /proc/pid/fd/
执行此操作的好方法是修改代码以跟踪打开文件的时间:
然后,使用
log_open
而不是open
打开文件。您甚至可以做一些更古怪的事情,例如修改File
类以记录自身。上面的链接问题对此进行了介绍。可能存在涉及垃圾收集器或查找 __dict__ 之类的恶心、肮脏的黑客,但您不想这样做,除非您绝对非常认真必须。
The nice way of doing this would be to modify your code to keep track of when it opens a file:
Then, use
log_open
instead ofopen
to open files. You could even do something more hacky, like modifying theFile
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.如果你使用的是 python 2.5+,你可以使用
with
关键字(尽管 2.5 需要 `from future import with_statement)我不知道需要什么样的灾难性失败bork the
with
语句,但我认为这是一个非常糟糕的语句。在WinXP上,我的快速不科学测试:然后用Windows任务管理器杀死进程仍然将数据写入文件。
If you're using python 2.5+ you can use the
with
keyword (though 2.5 needs `from future import with_statement)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:and then killing the process with Windows Task Manager still wrote the data to file.