在 python 中访问内存堆

Accessing the memory heap in python

有没有办法访问Python中的内存堆?我感兴趣的是能够访问在 运行 实例的内存中分配的 所有 对象。

您无法获得直接 访问权限,但the gc module should do most of what you want. A simple gc.get_objects() 调用将return 收集器跟踪的所有对象。这不是 一切,因为 CPython 垃圾收集器只关心潜在的引用循环(所以内置类型不能引用其他对象,例如 intfloatstr 等)不会出现在结果 list 中,但它们都会被 something 引用 list(如果不是,它们的引用计数将为零并且它们将被处理掉)。

除此之外,您可能会从 inspect 模块中获得一些更有针对性的用途,尤其是 stack frame inspection, using the traceback module 用于“轻松格式化”或手动挖掘半文档化的框架对象本身,或者其中允许您将范围缩小到堆栈框架上的特定活动范围。

对于最接近堆的解决方案,您可以在您的代码中使用the tracemalloc module to trace and record allocations as they happen, or the pdb debugger to do live introspection from the outside (possibly adding breakpoint() calls,使其在到达该点时自动停止,让您环顾四周。