什么会导致python内存泄漏? [英] What can cause a memory leak in python?

查看:249
本文介绍了什么会导致python内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Python:由于您的代码,Python中是否可能发生实际的内存泄漏?

Possible Duplicate:
Python: Is it possible to have an actual memory leak in Python because of your code?

由于python垃圾收集器处理对循环引用的检测(对象A引用对象B,对象B引用对象A),所以我想知道什么会导致python代码中的内存泄漏?您能否提供特定的代码示例,这些示例将创建垃圾回收器无法处理的无法访问的内存区域,或者这是不可能的事情?

Since the python garbage collector handles detection of circular references (object A referencing Object B and Object B referencing Object A), I was wondering what could cause a memory leak in python code? Can you provide specific examples of code that would create an inaccessible region of memory that the garbage collector could not handle or is such a thing impossible?

任何例子都值得赞赏!

推荐答案

您可以使用 gc —垃圾收集器接口模块

gc.garbage :

收集器发现的对象列表 ,但无法释放(无法收集的对象).经过 默认情况下,此列表仅包含具有__del__()方法的对象. [1] 具有__del__()方法并且是引用循环的一部分的对象 导致整个参考周期无法收集,包括 对象不一定在循环中,而是只能从循环中到达. Python不会自动收集此类周期,因为通常, Python无法猜测运行命令的安全顺序 __del__()方法.如果您知道安全的订单,则可以通过检查垃圾清单并明确中断由于以下原因导致的周期来强制执行此问题: 您列表中的对象.请注意,这些对象保持活动状态 即使是这样,因为它们位于垃圾清单中,所以它们应该是 也从垃圾中删除.例如,在中断循环后,执行del gc.garbage[:]清空列表.通常最好避免 通过不创建包含带有__del__()的对象的循环来解决此问题. 方法和垃圾可以在这种情况下进行检查,以确认没有 这样的循环正在建立.

gc.garbage:

A list of objects which the collector found to be unreachable but could not be freed (uncollectable objects). By default, this list contains only objects with __del__() methods. [1] Objects that have __del__() methods and are part of a reference cycle cause the entire reference cycle to be uncollectable, including objects not necessarily in the cycle but reachable only from it. Python doesn’t collect such cycles automatically because, in general, it isn’t possible for Python to guess a safe order in which to run the __del__() methods. If you know a safe order, you can force the issue by examining the garbage list, and explicitly breaking cycles due to your objects within the list. Note that these objects are kept alive even so by virtue of being in the garbage list, so they should be removed from garbage too. For example, after breaking cycles, do del gc.garbage[:] to empty the list. It’s generally better to avoid the issue by not creating cycles containing objects with __del__(). methods, and garbage can be examined in that case to verify that no such cycles are being created.

这篇关于什么会导致python内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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