python使用gc.get_objects()查看运行时对象,,从python2.2开始


从python2.2开始允许开发人员可以通过get_objects()方法获得被垃圾回收器控制的对象列表。 通过这种方式可以获得运行时程序中都有什么对象。

import gcimport inspectexclude = [    "function",    "type",    "list",    "dict",    "tuple",    "wrapper_descriptor",    "module",    "method_descriptor",    "member_descriptor",    "instancemethod",    "builtin_function_or_method",    "frame",    "classmethod",    "classmethod_descriptor",    "_Environ",    "MemoryError",    "_Printer",    "_Helper",    "getset_descriptor",    ]def dumpObjects():    gc.collect()    oo = gc.get_objects()    for o in oo:        if getattr(o, "__class__", None):            name = o.__class__.__name__            if name not in exclude:                filename = inspect.getabsfile(o.__class__)                            print "Object of class:", name, "...",                print "defined in file:", filename                if __name__=="__main__":    class TestClass:        pass    testObject1 = TestClass()    testObject2 = TestClass()    dumpObjects()

评论关闭