查找python中所有对象的引用 [英] Find all references to an object in python

查看:131
本文介绍了查找python中所有对象的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中查找对象的所有引用的好方法是什么?

我问的原因是它看起来像我们有一个内存泄漏。我们正在从Web浏览器将图像文件上传到服务器。每当我们这样做时,服务器上的内存使用率上升到刚刚上传的文件的大小。这个记忆永远不会被python垃圾回收发布,所以我认为即使在每个请求结束时,也许有些参考文献指向没有被删除或超出范围的图像数据。

The reason I ask is that it looks like we have a "memory leak". We are uploading image files to the server from a web browser. Each time we do this, the memory usage goes up on the server goes up proportionately to the size of the file that was just uploaded. This memory is never getting released by the python garbage collection, so I'm thinking that there are probably stray references pointing to the image data that are not getting deleted or going out of scope, even at the end of each request.

我认为能够问python会很好:什么参考依然指向这个内存?所以我可以弄清楚什么是保持垃圾收集免于释放。

I figure it would be nice to be able to ask python: "What references are still pointing to this memory?" so that I can figure out what is keeping the garbage collection from freeing it.

目前,我们在Heroku服务器上运行Python和Django。

Currently we are running Python and Django on a Heroku server.

非常感谢任何建议和想法,非常感谢!

Any suggestions and ideas are appreciated, thanks so much!

推荐答案

Python的标准库包含垃圾收集器API的 gc 模块。您可能想要的功能之一是

Python's standard library has gc module containing garbage collector API. One of the function you possible want to have is

gc.get_objects()

此函数返回垃圾回收器当前跟踪的所有对象的列表。下一步是分析它。

This function returns list of all objects currently tracked by garbage collector. The next step is to analyze it.

如果你知道要跟踪的对象,你可以使用 sys module getrefcount 功能:

If you know the object you want to track you can use sys module's getrefcount function:

>>> x = object()
>>> sys.getrefcount(x)
2
>>> y = x
>>> sys.getrefcount(x)
3

这篇关于查找python中所有对象的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆