Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python如何关闭已被gc';预计起飞时间?_Python_File_Garbage Collection_Del - Fatal编程技术网

python如何关闭已被gc';预计起飞时间?

python如何关闭已被gc';预计起飞时间?,python,file,garbage-collection,del,Python,File,Garbage Collection,Del,我一直认为,如果文件在未关闭的情况下打开,则会泄漏,但我只是验证了如果输入以下代码行,文件将关闭: >>> f = open('somefile.txt') >>> del f 纯粹出于好奇,这是怎么回事?我注意到该文件没有包含\uuuudel\uu方法。因此使用with语句 对于Python2.5,使用 from __future__ import with_statement (对于Python2.6或3.x,不执行任何操作) 最好的猜测是,因为文件类

我一直认为,如果文件在未关闭的情况下打开,则会泄漏,但我只是验证了如果输入以下代码行,文件将关闭:

>>> f = open('somefile.txt')
>>> del f

纯粹出于好奇,这是怎么回事?我注意到该文件没有包含
\uuuu
del
\uu
方法。

因此使用with语句

对于Python2.5,使用

from __future__ import with_statement
(对于Python2.6或3.x,不执行任何操作)


最好的猜测是,因为文件类型是内置类型,所以解释器本身负责在垃圾收集时关闭文件


或者,您只能在python解释器退出后进行检查,并且所有“泄漏”的文件句柄都将关闭。

在CPython中,至少在解除分配文件对象时,文件将关闭。请参阅CPython源代码中
Objects/fileobject.c
中的
file\u dealloc
函数。对于C类型,Dealloc方法有点像
\uuuu del\uuu
,除了没有
\uu del\uu
固有的一些问题之外,Python除了垃圾收集之外还使用引用计数和确定性销毁。当不再引用对象时,该对象将立即释放。释放文件将关闭它

这与Java不同,Java中只有不确定的垃圾收集。这意味着您无法知道对象何时释放,因此必须手动关闭该文件


请注意,引用计数并不完美。您可以拥有循环引用的对象,而该对象无法从程序访问。这就是Python除了引用计数之外还有垃圾收集的原因。

我也这么认为。但是在Python2.5.1的OSX上,我发布的代码行会导致Python解释器释放文件(在活动监视器中验证)。Python应该在收集文件时关闭文件。我一直在查找fileobject.c中发生这种情况的地方,但它不在那里。它可能在gc机制的某个地方,这就是我接下来要看的地方。我喜欢这个问题。看起来我在fileobject.c中漏掉了它(参见Gallagher)。我真希望我能更好地理解CPython的内部结构。它不在gc模块中。Python的C实现使用引用计数,Devin正在查找的代码位于Py_DECREF、Py_XDECREF和Py_DECREF中的object.h中。“del f”释放了最后一个引用,它触发了_Py_dealoc调用。我对“primitive type”(从Java接收)的理解并没有将文件作为一个原语,因为Python中没有原语。我认为HUAGHAGUAH的意思是说“内置类型”。:)为了澄清,del在垃圾收集期间被调用,在Python的C实现中,当没有更多的文件对象引用时,就会出现文件对象。
with open( "someFile", "rU" ) as aFile:
    # process the file
    pass
# At this point, the file was closed by the with statement.
# Bonus, it's also out of scope of the with statement,
# and eligible for GC.