Python - 在内存中查找当前对象

Inf*_*ner 5 python memory python-3.x

有没有办法找到当前在内存中的对象,包括它们的名称、它们所在的位置和模块名称等?

我在任务管理器中 main() 方法之前的进程 Python.exe 的内存占用为 15MB。

main 方法完成第一次迭代后,进程 Python.exe 内存大小为 250MB。

我想了解哪些对象仍在内存中,以便我可以删除它们

while True:
 # print current object details
 main() 
 # print current object details
Run Code Online (Sandbox Code Playgroud)

use*_*ica 6

不可以。Python 中没有办法找到所有对象。此外,大多数对象没有名称,并且对象“位置”并不像您想象的那样工作。

与您要查找的内容最接近的是gc.get_objects,它返回所有 GC 跟踪的对象的列表。这不是所有对象的列表,也没有告诉您为什么对象仍然存在。您可以使用 获取对象的 GC 跟踪引用gc.get_referrers,但 GC 并不知道所有引用。

即使您确保不再需要的对象无法访问,并且即使它们的内存被回收,这仍然并不意味着 Python 实际上会将内存返回给操作系统。完成这一切后,您的内存使用量可能仍为 250 MB。


小智 5

获取当前加载的变量

该函数dir()将列出所有加载的环境变量,例如:

a = 2
b = 3
c = 4
print(dir())
Run Code Online (Sandbox Code Playgroud)

将返回

['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'c']
Run Code Online (Sandbox Code Playgroud)

查找下面的文档内容dir

dir(...) dir([object]) -> 字符串列表

If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
  for a module object: the module's attributes.
  for a class object:  its attributes, and recursively the attributes
    of its bases.
  for any other object: its attributes, its class's attributes, and
    recursively the attributes of its class's base classes.
Run Code Online (Sandbox Code Playgroud)

获取变量方法和属性

您还可以用来dir()列出与对象关联的方法和属性,为此您应使用:dir(<name of object>)

获取当前加载的变量的大小

如果您希望评估加载的变量/对象的大小,您可以使用sys.getsizeof(),如下所示:

['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'c']
Run Code Online (Sandbox Code Playgroud)

sys.getsizeof()获取对象的大小(以字节为单位)(有关更多信息,请参阅这篇文章)

包起来

您可以将此功能组合到某种循环中,如下所示

import sys
a =2
b = 3
c = 4
d = 'John'
e = {'Name': 'Matt', 'Age': 32}

for var in dir():
    print(var, type(eval(var)), eval(var), sys.getsizeof(eval(var)))
Run Code Online (Sandbox Code Playgroud)

希望有帮助!

  • `dir` 与环境变量无关。另外,sys.getsizeof 是“浅薄的”——它不考虑参数引用的其他对象的大小。例如,如果您向其传递一个字典,它将不包括字典的键和值的大小。(有些项目试图计算“深度 sizeof”,但可靠性程度不同。) (2认同)