Find all references to an object in python(在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 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.
推荐答案
Python 的标准库有 gc
模块,其中包含垃圾收集器 API.您可能想要的功能之一是
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
模块的 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中查找对对象的所有引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在python中查找对对象的所有引用


基础教程推荐
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01