def memory_dump(show_cycles=True, show_objects=False):
print "\nGARBAGE:"
gc.collect()
garbage = gc.garbage[:]
if show_cycles:
nodes = {id(obj): Node(obj) for obj in garbage}
for obj in garbage:
nodes[id(obj)].successors = tuple(nodes[id(s)] for s in gc.get_referents(obj) if id(s) in nodes)
nodes[id(obj)].visitable_successors = deque(nodes[id(obj)].successors)
cycles = set()
remaining_nodes = nodes.copy()
while remaining_nodes:
path = [next(remaining_nodes.itervalues())]
while path:
node = path[-1]
remaining_nodes.pop(id(node.object), None)
if node.visitable_successors:
successor = node.visitable_successors.pop()
if successor in path:
cycles.add(Cycle(n.object for n in path[path.index(successor):]))
else:
path.append(successor)
else:
node.visitable_successors = deque(node.successors)
path.pop(-1)
for node in nodes.itervalues():
node.successors = node.visitable_successors = None
print "\nCOLLECTABLE CYCLES:"
for cycle in (c for c in cycles if c.collectable):
print cycle
print "\nUNCOLLECTABLE CYCLES:"
for cycle in (c for c in cycles if not c.collectable):
print cycle
if show_objects:
try:
import fcntl, struct, sys, termios
console_width = struct.unpack('HHHH', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, struct.pack('HHHH', 0, 0, 0, 0)))[1]
except Exception:
console_width = 80
print "\nGARBAGE OBJECTS:"
for x in garbage:
s = str(x)
if len(s) > console_width-2:
s = s[:console_width-5] + '...'
print "%s\n %s" % (type(x), s)
评论列表
文章目录