53

假设在 python shell (IDLE) 中我定义了一些类、函数、变量。还创建了类的对象。然后我删除了一些对象并创建了一些其他对象。稍后,我如何才能知道内存中当前活动的对象、变量和方法定义是什么?

4

4 回答 4

66

是的。

>>> import gc
>>> gc.get_objects()

并不是说你会发现那很有用。他们有很多。:-) 刚开始 Python 时就有超过 4000 个。

可能更有用的是所有在本地活动的变量:

>>> locals()

全球活跃的一个:

>>> globals()

(请注意,Python 中的“全局”本身并不是真正的全局。为此,您需要gc.get_objects()上述内容,并且如上所述,您不太可能发现有用)。

于 2010-12-16T08:29:29.017 回答
10

该函数gc.get_objects()不会找到所有对象,例如找不到 numpy 数组。

import numpy as np
import gc

a = np.random.rand(100)
objects = gc.get_objects()
print(any[x is a for x in objects])
# will not find the numpy array

您将需要一个扩展所有对象的函数,如此处所述

# code from https://utcc.utoronto.ca/~cks/space/blog/python/GetAllObjects
import gc
# Recursively expand slist's objects
# into olist, using seen to track
# already processed objects.
def _getr(slist, olist, seen):
  for e in slist:
    if id(e) in seen:
      continue
    seen[id(e)] = None
    olist.append(e)
    tl = gc.get_referents(e)
    if tl:
      _getr(tl, olist, seen)

# The public function.
def get_all_objects():
  """Return a list of all live Python
  objects, not including the list itself."""
  gcl = gc.get_objects()
  olist = []
  seen = {}
  # Just in case:
  seen[id(gcl)] = None
  seen[id(olist)] = None
  seen[id(seen)] = None
  # _getr does the real work.
  _getr(gcl, olist, seen)
  return olist

现在我们应该能够找到大多数对象

import numpy as np
import gc

a = np.random.rand(100)
objects = get_all_objects()
print(any[x is a for x in objects])
# will return True, the np.ndarray is found!
于 2019-03-06T15:10:01.837 回答
5

尝试globals()

于 2010-12-16T08:26:44.000 回答
5

dir()哪个将实例化的对象作为列表输出呢?我刚刚用了这个: [x for x in dir() if x.lower().startswith('y')]

于 2020-07-17T21:16:33.633 回答