gc
— 垃圾收集器接口
¶
此模块提供到可选垃圾收集器的接口。它提供禁用收集器、微调收集频率及设置调试选项的能力。它还提供对收集器能发现却无法释放的无法企及对象的访问。由于收集器会增补 Python 已使用的引用计数,因此若确信程序不会创建引用循环,则可以禁用收集器。自动收集可以被禁用通过调用
gc.disable()
。要调试泄漏程序调用
gc.set_debug(gc.DEBUG_LEAK)
。预告,这包括
gc.DEBUG_SAVEALL
,导致垃圾收集对象被保存在 gc.garbage 中以供审查。
The
gc
模块提供下列函数:
- gc. enable ( ) ¶
-
启用自动垃圾收集。
- gc. disable ( ) ¶
-
禁用自动垃圾收集。
- gc. isenabled ( ) ¶
-
返回
True如果自动收集被启用。
- gc. collect ( generation = 2 ) ¶
-
没有自变量,运行完整收集。可选自变量 generation 可以是指定要收集哪一代 (从 0 到 2) 的整数。
ValueErroris raised if the generation number is invalid. The sum of collected objects and uncollectable objects is returned.由许多内置类型维护的释放列表会被清零,每当运行完整收集或最高 2 世代的收集时。某些释放列表中的所有项可能不会被释放,由于特定实现原因,尤其是
float.The effect of calling
gc.collect()while the interpreter is already performing a collection is undefined.
- gc. set_debug ( flags ) ¶
-
设置垃圾收集调试标志。调试信息会被写入到
sys.stderr. See below for a list of debugging flags which can be combined using bit operations to control debugging.
- gc. get_debug ( ) ¶
-
返回目前设置的调试标志。
- gc. get_objects ( generation = None ) ¶
-
Returns a list of all objects tracked by the collector, excluding the list returned. If generation 不是
None, return only the objects tracked by the collector that are in that generation.3.8 版改变: New generation 参数。
引发 审计事件
gc.get_objects采用自变量generation.
- gc. get_stats ( ) ¶
-
Return a list of three per-generation dictionaries containing collection statistics since interpreter start. The number of keys may change in the future, but currently each dictionary will contain the following items:
-
collectionsis the number of times this generation was collected; -
collectedis the total number of objects collected inside this generation; -
uncollectableis the total number of objects which were found to be uncollectable (and were therefore moved to thegarbagelist) inside this generation.
Added in version 3.4.
-