易截截图软件、单文件、免安装、纯绿色、仅160KB

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 -


相关文档:

[python]重定向输出

  调用一个控制台程序,获取它的标准输出,或把它的标准输出重定向到界面上,这里只介绍如何获取它的标准输出,因为原理都一样的。
使用python2.5的subprocess模块来实现。
import sys
import subprocess
def RunShellWithReturnCode(command, print_output=False,
universal_newline ......

使用pdb进行python的调试

1 在想要插入断点的地方插入代码
                import pdb
                pdb.set_trace()
2然后使用指令进行debug
查看代码上下文,l(小写L)
监视变量 ......

python 的函数Decorators

Decorators是python中比较难以理解的东西,当然如果你接触过java的annotation,会发现这个Decorators在语法上非常的相似,但是两者的设计动机却没什么共同点;
这里讲的python中的decorators是对python中的function/method做装饰,这些修饰仅是当声明一个函数或者方法的时候,才会应用的额外调用。
python中的decorator分 ......

Python获取操作系统版本信息

    最近,想在我的YouMoney(http://code.google.com/p/youmoney/)里面增加提取用户操作系统版本信息。比如windows用户,可能要返回Windows XP ,或者Windows 2003, 苹果用户应该返回Mac OS X 10.5.8。用了很多办法,包括在mac系统里调用系统命令,取环境变量,等等。最后无意发现,原来python里里面有个pl ......

python string和PyQt的QString的区别

python string和PyQt的QString的区别 以下在Python2.6和PyQt4.4.4 for
Python2,6环境下讨论: Python中有两种有关字符的类型:Python string object和Python Unicode
object。主要使用Python string object进行数据输入输出。 PyQt中与之相对应的字符有关类
python string和PyQt的QString的区别
以下在Python2.6和PyQt4 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号