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 在想要插入断点的地方插入代码
import pdb
pdb.set_trace()
2然后使用指令进行debug
查看代码上下文,l(小写L)
监视变量 ......
下面列出Python正则表达式的几种匹配用法:
1.测试正则表达式是否匹配字符串的全部或部分
regex=ur"" #正则表达式
if re.search(regex, subject):
do_something()
else:
do_anotherthing()
2.测试正则表达式是否匹配整个字符串
regex=ur"\Z" #正则表达式末尾以\ ......
1.c调用python:
实例代码:
main.c调用test.py的
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//main.c
#include <windows.h>
......
python的C、c++扩展
http://blog.chinaunix.net/u3/110228/showart_2148725.html
python的强大不仅表现在其功能上,而且还表现在其扩展能力上。
使用C/C++很容易编写python的模块,扩展python的功能。
同时将性能要求比较高的代码使用C/C++编写,能更好的弥补
脚本语言执行速度慢的缺陷。
1. python的C语言扩展
1.1 ......
下载安装MySQLdb
http://sourceforge.net/projects/mysql-python/ 好像没看到windows版本for python2.6的下载,网上搜索到一个
http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe
安装后import MySQLdb会出现 DeprecationWarning: the sets module is deprecated 这样一个警告,google之
......