在python中打开文件描述符 [英] opened file descriptors in python

查看:136
本文介绍了在python中打开文件描述符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在IPython3 shell中使用此代码时

when I use this code in IPython3 shell

 >>>data = open('file').read()

,然后检查打开的文件描述符:

and then check open file descriptors:

 lsof | grep file

我发现空列表

以及当我使用此功能时:

and when I use this:

>>>open('file')

lsof显示两项.问题是,为什么第一个操作关闭fd而第二个不关闭?我以为垃圾收集器必须删除没有引用的文件对象.

lsof shows two items. The question is why first operation closes fd while second doesn't? I supposed that garbage collector must delete file object with no refs.

当我重新分配值时,我知道解释器中的'_'var

I know about '_' var in interpreter, when I reassign value

>>>111
>>>_
111

,但描述符保持打开状态. 当我重复

but descriptors remain open. when I repeat

>>>open('file')

n次有2 * n个打开的描述符

n times there are 2 * n opened descriptors

推荐答案

在第二个示例中,文件句柄由交互式解释器变量_保留,该变量允许您访问最后计算的表达式.如果计算另一个表达式,例如1+1,您会注意到lsof不再将文件报告为打开.

In the second example the file handle is retained by the interactive interpreter variable _, which allows you to access the last evaluated expression. If you evaluate another expression, such as 1+1, you will note that the file is no longer reported by lsof as open.

正如Mike Byers指出的,此行为特定于CPython,甚至在特定情况下也适用于文件对象的使用方式.要确保无论代码如何执行都关闭文件,请使用with语句:

As pointed out by Mike Byers, this behavior is specific to CPython, and even then to precise circumstances of how the file object is used. To make sure the file is closed regardless of how the code is executed, use a with statement:

with open('file') as fp:
    data = fp.read()

这篇关于在python中打开文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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