fun*_*orn 93 python memory-management dir
我几天来一直在寻找这个问题的准确答案但是没有任何好处.我不是一个完整的编程初学者,但即使在中级水平也是如此.
当我在Python的shell中时,我输入:dir()我可以看到当前范围(主要块)中所有对象的所有名称,其中有6个:
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
Run Code Online (Sandbox Code Playgroud)
然后,当我声明一个变量时,例如x = 10,它会自动添加到内置模块下的对象列表中dir(),当我dir()再次键入时,它会立即显示:
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'x']
Run Code Online (Sandbox Code Playgroud)
功能,类等也是如此.
如何在不删除开头可用的标准6的情况下删除所有这些新对象?
我在这里读过"内存清理","清理控制台",它会从命令提示符窗口中删除所有文本:
>>> import sys
>>> clear = lambda: os.system('cls')
>>> clear()
Run Code Online (Sandbox Code Playgroud)
但这一切都与我想要实现的目标无关,它并没有清除所有使用过的对象.
Mar*_*ers 121
您可以删除个人姓名del:
del x
Run Code Online (Sandbox Code Playgroud)
或者你可以从globals()对象中删除它们:
for name in dir():
if not name.startswith('_'):
del globals()[name]
Run Code Online (Sandbox Code Playgroud)
这只是一个示例循环; 它在防御上只删除了不以下划线开头的名称,这使得(非非无理的)假设您在解释器的开头只使用了没有下划线的名称.如果您真的想彻底,可以使用硬编码的名称列表(白名单).除了退出并重新启动解释器之外,没有内置函数可以为您清除.
您导入的模块(import os)将继续导入,因为它们被引用sys.modules; 后续导入将重用已导入的模块对象.您只是在当前的全局命名空间中没有对它们的引用.
Eye*_*ear 55
是.有一种简单的方法可以删除iPython中的所有内容.在iPython控制台中,只需键入:
%reset
Run Code Online (Sandbox Code Playgroud)
然后系统会要求您确认.按y.如果您不想看到此提示,只需键入:
%reset -f
Run Code Online (Sandbox Code Playgroud)
这应该工作..
Far*_*din 11
您可以使用python垃圾收集器:
import gc
gc.collect()
Run Code Online (Sandbox Code Playgroud)
If you are in an interactive environment like Jupyter or ipython you might be interested in clearing unwanted var's if they are getting heavy.
The magic-commands reset and reset_selective is vailable on interactive python sessions like ipython and Jupyter
1) reset
resetResets the namespace by removing all names defined by the user, if called without arguments.
in and the out parameters specify whether you want to flush the in/out caches. The directory history is flushed with the dhist parameter.
reset in out
Run Code Online (Sandbox Code Playgroud)
Another interesting one is array that only removes numpy Arrays:
reset array
Run Code Online (Sandbox Code Playgroud)
2) reset_selective
Resets the namespace by removing names defined by the user. Input/Output history are left around in case you need them.
Clean Array Example:
In [1]: import numpy as np
In [2]: littleArray = np.array([1,2,3,4,5])
In [3]: who_ls
Out[3]: ['littleArray', 'np']
In [4]: reset_selective -f littleArray
In [5]: who_ls
Out[5]: ['np']
Run Code Online (Sandbox Code Playgroud)
Source: http://ipython.readthedocs.io/en/stable/interactive/magics.html
实际上python会回收不再使用的内存。这称为垃圾收集,这是python中的自动过程。但是如果你想这样做,那么你可以删除它del variable_name。您也可以通过将变量分配给None
a = 10
print a
del a
print a ## throws an error here because it's been deleted already.
Run Code Online (Sandbox Code Playgroud)
从未引用的 Python 对象中真正回收内存的唯一方法是通过垃圾收集器。del 关键字只是从一个对象中解除一个名称的绑定,但该对象仍然需要被垃圾回收。您可以使用 gc 模块强制垃圾收集器运行,但这几乎可以肯定是过早的优化,但它有其自身的风险。使用del没有实际效果,因为这些名称无论如何都会在超出范围时被删除。
| 归档时间: |
|
| 查看次数: |
216177 次 |
| 最近记录: |