在python中查找对对象的所有引用

2023-07-05Python开发问题
39

本文介绍了在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中查找对对象的所有引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11