如何在python中获取所有初始化对象和函数定义的列表?

41 python memory python-idle

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

Len*_*bro 51

是.

>>> import gc
>>> gc.get_objects()
Run Code Online (Sandbox Code Playgroud)

并不是说你会觉得有用.它们中有很多.:-)当你启动Python时超过4000.

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

>>> locals()
Run Code Online (Sandbox Code Playgroud)

而全球活跃的一个:

>>> globals()
Run Code Online (Sandbox Code Playgroud)

(请注意,Python中的"全局"并不是真正全局的.为此,您需要gc.get_objects()上述内容,并且您不太可能找到有用的内容,如上所述).

  • 对.get_objects给出你想要的东西,locals()和globals()你想要的.;-) (13认同)
  • 谢谢.正是我想要的.但是`gc.get_objects()`给出了巨大的转储.`locals()`和`globals()`做得很好. (3认同)

skj*_*rns 6

该函数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
Run Code Online (Sandbox Code Playgroud)

您将需要一个可扩展的所有对象的功能,如解释在这里

# 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
Run Code Online (Sandbox Code Playgroud)

现在我们应该能够找到大多数物体

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!
Run Code Online (Sandbox Code Playgroud)


use*_*515 5

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