python - 在程序运行期间查看生成列表

标签 python debugging memory memory-management garbage-collection

故事:

Nina Zakharenko's PyCon talk 期间关于 Python 中的内存管理,她解释了 分代垃圾收集 在 Python 中的工作方式,并指出:

Python maintains a list of every object created as a program is run. Actually, it makes 3:

  • generation 0
  • generation 1
  • generation 2

问题:

为了更深入地了解 Python 中的内存管理以及调试内存泄漏,我如何观察/观察在程序运行期间从所有 3 代列表中添加和删除了哪些对象 ?

我浏览了gc module ,但还没有找到获取当前世代列表值的相关方法。

最佳答案

正如我们在评论中讨论的那样,我认为没有办法直接从 python 访问生成列表,你可以设置一些调试标志,在 python2 中你可以使用以下来报告可以或不可以的对象收集:

import gc

gc.set_debug(gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_COLLECTABLE | gc.DEBUG_OBJECTS )

在 python3 中,使用以下内容将为您提供一些生成输出和有关可收集和不可收集对象的信息:

import gc

gc.set_debug(gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_COLLECTABLE  | gc.DEBUG_STATS)

你会得到如下输出:

gc: collecting generation 2...
gc: objects in each generation: 265 4454 0
gc: collectable <function 0x7fad67f77b70>
gc: collectable <tuple 0x7fad67f6f710>
gc: collectable <dict 0x7fad67f0e3c8>
gc: collectable <type 0x285db78>
gc: collectable <getset_descriptor 0x7fad67f095e8>
gc: collectable <getset_descriptor 0x7fad67f09630>
gc: collectable <tuple 0x7fad67f05b88>
gc: done, 7 unreachable, 0 uncollectable, 0.0028s elapsed.
gc: collecting generation 2...

根据 gc.DEBUG_SAVEALL 的泄漏设置后,所有找到的无法访问的对象都将被附加到垃圾中而不是被释放。这对于调试泄漏程序很有用:

import gc

gc.set_debug(gc.DEBUG_SAVEALL)

在python3中,还可以附加一个回调,在gc启动和结束时运行,一个简单的例子:

def f(phase, info):
    if phase == "start":
        print("starting garbage collection....")
    else:
        print("Finished garbage collection.... \n{}".format("".join(["{}: {}\n".format(*tup) for tup in info.items()])))

        print("Unreachable objects: \n{}".format(
            "\n".join([str(garb) for garb in gc.garbage])))
        print()


 gc.callbacks.append(f)

gc.DEBUG_SAVEALL 与该函数结合将显示所有无法访问的对象,这与设置 DEBUG_COLLECTABLEDEBUG_LEAK 没有太大区别但是添加 callback 的一个示例.

关于python - 在程序运行期间查看生成列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37737753/

相关文章:

python - 经过训练的机器学习模型太大

python - 如何在 Google App Engine 中正确保存表单数据

javascript - 获取有关 Javascript 变量的所有信息

qt - 在 WinDbg 中调试 QT 应用程序

分析内存分配器的正确方法

c - 查找堆栈的返回地址

Python,从内存中删除密码

python - 删除06、07等数字前的0

python - django-filter:如何连接列

c++ - LD_DEBUG=Windows Visual Studio 的文件?