【问题标题】:Python - Find current objects in memoryPython - 在内存中查找当前对象
【发布时间】:2020-07-01 23:13:45
【问题描述】:

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

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

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

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

while True:
 # print current object details
 main() 
 # print current object details

【问题讨论】:

  • print(python.memory.objects()) 没有用吗?
  • @10Rep:没有这样的事情。
  • @user2357112supportsMonica 我知道,这是个笑话。
  • @10Rep:比起取悦他们,它更有可能使人们感到困惑和沮丧,因为您将其呈现为就好像它是手头问题的实际解决方案一样。

标签: python python-3.x memory


【解决方案1】:

没有。没有办法在 Python 中找到所有对象。此外,大多数对象没有名称,并且对象“位置”的工作方式与您认为的工作方式不同。

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

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

【讨论】:

  • GC 是垃圾回收,顺便说一下。
【解决方案2】:

获取当前加载的变量

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

a = 2
b = 3
c = 4
print(dir())

会回来

['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'c']

在下面找到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.

获取变量方法和属性

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

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

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

sys.getsizef(a)
sys.getsizof(<name of variable>)

sys.getsizeof() 获取对象的大小(以字节为单位)(请参阅this post 了解更多信息)

结束

你可以将这个功能组合在某种循环中

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)))

希望有帮助!

【讨论】:

  • dir 与环境变量无关。此外,sys.getsizeof 是“浅”的——它不考虑参数引用的其他对象的大小。例如,如果您向它传递一个 dict,它将不包括该 dict 的键和值的大小。 (有些项目试图计算“深度大小”,具有不同程度的可靠性。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
  • 2013-02-17
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
  • 2011-07-02
相关资源
最近更新 更多