假设在python shell(IDLE)中我定义了一些类,函数和变量。还创建了类的对象。然后我删除了一些对象并创建了其他一些对象。在以后的某个时间点,我如何才能知道内存中活动的当前活动对象,变量和方法定义是什么?
是。
>>> import gc
>>> gc.get_objects()
并不是说你会觉得有用。它们中有很多。 :-)当你启动Python时超过4000。
可能更有用的是本地活动的所有变量:
>>> locals()
而全球活跃的一个:
>>> globals()
(请注意,Python中的“全局”并不是真正全局的。为此,您需要上面的gc.get_objects()
,并且您不太可能找到有用的,如上所述)。
函数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
您将需要一个扩展所有对象的函数,如here所述
# 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
现在我们应该能够找到most对象
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!