Python的内存泄漏及gc模块的使用
Python的内存泄漏及gc模块的使用
-- 6.11日错误修正版
Horin|贺勤
Email: horin153@msn.com
Blog:
http://blog.csdn.net/horin153/
在 Python
中,为了解决内存泄漏问题,采用了对象引用计数,并基于引用计数实现自动垃圾回收。
因为 Python
有了自动垃圾回收功能,不少初学者就认为自己从此过上了好日子,不必再受内存泄漏的骚扰了。但如果查看一下 Python 文档对 __del__()
函数的描述,就知道好日子里也是有阴云的。下面摘抄一点文档内容:
Some common situations that may
prevent the reference count of an object from going to zero include:
circular references between objects (e.g., a doubly-linked list or a
tree data structure with parent and child pointers); a reference to the
object on the stack frame of a function that caught an exception (the
traceback stored in sys.exc_traceback keeps the stack frame alive); or a
reference to the object on the stack frame that raised an unhandled
exception in interactive mode (the traceback stored in
sys.last_traceback keeps the stack frame alive).
可见,有 __del__()
函数的对象间的循环引用是导致内存泄漏的主凶。特别说明:对没有 __del__() 函数的 Python
对象间的循环引用,是可以被自动垃圾回收掉的。
如何知道一个对象是否内存泄漏了呢?
方法一、当你认为一个对象应该被销毁时(即引用计数为 0),可以通过 sys.getrefcount(obj)
来获取对象的引用计数,并根据返回值是否为 0 来判断是否内存泄漏。如果返回的引用计数不为 0,说明在此刻对象 obj
是不能被垃圾回收器回收掉的。
方法二、也可以通过 Python 扩展模块 gc 来查看不能回收的对象的详细信息。
首先,来看一段正常的测试代码:
#--------------- code begin --------------
#
-*- coding: utf-8 -
相关文档:
软件准备:
1.eclipse开发包,下载地址:http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/galileo/SR2/eclipse-java-galileo-SR2-win32.zip
2.pydev插件,下载地址:http://sourceforge.net/projects/pydev/files/pydev/Pydev%201.5.4/org.python.pydev.feature-1.5.4.2010011921 ......
▾ hide table of contents
0. ↑ 显示完整目录
1. 深入#
2. 布尔类型#
3. 数值类型#
1. 将整数强制转换为浮点数及反向转换#
2. 常见数值运算#
3. 分数#
4. 三角函数#
5. 布尔上下文环境中的数值#
4. 列表#
1. 创建列表#
......
Programming Python, 2nd Edition (O'Reilly)
http://www.osbbs.com/dl/Programming Python, 2nd Edition (O'Reilly).chm
很全很经典了python学习入门资料
OReilly - Learning Python:
http://www.osbbs.com/dl/OReilly - Learning Python.chm
......
实验环境:windows xp + vim
文件:test.py。编码:ansi
我们的目标操作test.py中保存的非英文字母。
文件头的#encoding=utf8/gbk,这个是用来说明源文件的硬盘编码以便python识别[4]。
----------------------------------------------
输入:
x = '中文'
输出: 编译失败
编译时需要知道‘中文’的硬盘编 ......