易截截图软件、单文件、免安装、纯绿色、仅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]PLY模块 Lex/YACC的python实现

  PLY模块 是Lex/YACCPython 的实现,可以用来实现词法分析/语法分析,但如何用,还没研究,以后有时间再研究吧;
  主页: http://www.dabeaz.com/ply/
  pycparser模块 是使用PLY模块分析c语言语法的模块,没什么文档,但模块自带了例子和测试用例。
   主页: http://code.google.com/p/pycpa ......

使用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中datetime的比较方法使用


python中的datetime module是专门处理时间相关内容的模块,功能很强大,但是反而显得比较复杂。
一下代码是用来求从mysql中取到的timestamp和当前时间比较,求时间差的方法
import datetime
lasttime=a.get_last_timestamp(sid=40)[-1]["last_time"] #取到timestamp
delta = datetime.datetime.now()-lasttime   # ......

关于python unicode的实验

实验环境:windows xp + vim
文件:test.py。编码:ansi
我们的目标操作test.py中保存的非英文字母。
文件头的#encoding=utf8/gbk,这个是用来说明源文件的硬盘编码以便python识别[4]。
----------------------------------------------
输入:
x = '中文'
输出: 编译失败
编译时需要知道‘中文’的硬盘编 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号