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

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

问题描述

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

我问的原因是看起来我们有内存泄漏".我们正在从 Web 浏览器将图像文件上传到服务器.每次我们这样做时,服务器上的内存使用量与刚刚上传的文件的大小成正比.这个内存永远不会被 python 垃圾收集释放,所以我认为可能有指向图像数据的杂散引用,即使在每个请求结束时也不会被删除或超出范围.

我认为能够询问 python 会很好:哪些引用仍然指向这个内存?"这样我就可以找出是什么阻止了垃圾收集将其释放.

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

解决方案

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

gc.get_objects()

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

如果您知道要跟踪的对象,可以使用 sys 模块的 getrefcount 函数:

<预><代码>>>>x = 对象()>>>sys.getrefcount(x)2>>>y = x>>>sys.getrefcount(x)3

What is a good way to find all of the references to an object in 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.

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.

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

解决方案

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.

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天全站免登陆