Python 有没有办法从解释器的内存中删除创建的变量、函数等?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26545051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to delete created variables, functions, etc from the memory of the interpreter?
提问by funghorn
I've been searching for the accurate answer to this question for a couple of days now but haven't got anything good. I'm not a complete beginner in programming, but not yet even on the intermediate level.
几天来我一直在寻找这个问题的准确答案,但没有得到任何好处。我不是一个完整的编程初学者,但甚至还没有达到中级水平。
When I'm in the shell of Python, I type: dir()and I can see all the names of all the objects in the current scope (main block), there are 6 of them:
当我在 Python 的 shell 中时,我输入:dir()并且我可以看到当前作用域(主块)中所有对象的所有名称,其中有 6 个:
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
Then, when I'm declaring a variable, for example x = 10, it automatically adds to that lists of objects under built-in module dir(), and when I type dir()again, it shows now:
然后,当我声明一个变量时,例如x = 10,它会自动添加到内置模块下的对象列表中dir(),当我dir()再次输入时,它现在显示:
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'x']
The same goes for functions, classes and so on.
函数、类等也是如此。
How do I delete all those new objects without erasing the standard 6 which where available at the beginning?
如何删除所有这些新对象而不擦除开始时可用的标准 6?
I've read here about "memory cleaning", "cleaning of the console", which erases all the text from the command prompt window:
我在这里阅读了有关“内存清理”、“控制台清理”的内容,它们会从命令提示符窗口中删除所有文本:
>>> import sys
>>> clear = lambda: os.system('cls')
>>> clear()
But all this has nothing to do with what I'm trying to achieve, it doesn't clean out all used objects.
但这一切与我想要实现的目标无关,它并没有清除所有使用过的对象。
采纳答案by Martijn Pieters
You can delete individual names with del:
您可以使用以下命令删除单个名称del:
del x
or you can remove them from the globals()object:
或者您可以从globals()对象中删除它们:
for name in dir():
if not name.startswith('_'):
del globals()[name]
This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.
这只是一个示例循环;它防御性地仅删除不以下划线开头的名称,从而做出(并非没有道理的)假设您只在解释器的开头使用没有下划线的名称。如果您真的想要彻底,您可以使用硬编码的名称列表来代替(白名单)。除了退出并重新启动解释器之外,没有内置函数可以为您进行清除。
Modules you've imported (import os) are going to remain imported because they are referenced by sys.modules; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.
您已导入 ( import os) 的模块将保持导入状态,因为它们被sys.modules; 后续导入将重用已导入的模块对象。您只是不会在当前的全局命名空间中引用它们。
回答by d-coder
Actually python will reclaim the memory which is not in use anymore.This is called garbage collectionwhich is automatic process in python. But still if you want to do it then you can delete it by del variable_name. You can also do it by assigning the variable to None
实际上python会回收不再使用的内存。这称为垃圾收集,这是python中的自动过程。但是如果你想这样做,那么你可以删除它del variable_name。您也可以通过将变量分配给None
a = 10
print a
del a
print a ## throws an error here because it's been deleted already.
The only way to truly reclaim memory from unreferenced Python objects is via the garbage collector. The del keyword simply unbinds a name from an object, but the object still needs to be garbage collected. You can force garbage collector to run using the gc module, but this is almost certainly a premature optimization but it has its own risks. Using delhas no real effect, since those names would have been deleted as they went out of scope anyway.
从未引用的 Python 对象中真正回收内存的唯一方法是通过垃圾收集器。del 关键字只是从一个对象中解除一个名称的绑定,但该对象仍然需要被垃圾回收。您可以使用 gc 模块强制垃圾收集器运行,但这几乎可以肯定是过早的优化,但它有其自身的风险。使用del没有实际效果,因为这些名称无论如何都会在超出范围时被删除。
回答by EyesBear
Yes. There is a simple way to remove everything in iPython. In iPython console, just type:
是的。有一种简单的方法可以删除 iPython 中的所有内容。在 iPython 控制台中,只需键入:
%reset
Then system will ask you to confirm. Press y. If you don't want to see this prompt, simply type:
然后系统会要求您确认。按 y。如果您不想看到此提示,只需键入:
%reset -f
This should work..
这应该工作..
回答by user1767754
If you are in an interactive environment like Jupyteror ipythonyou might be interested in clearing unwanted var'sif they are getting heavy.
如果您处于交互式环境中,Jupyter或者ipython您可能有兴趣 清除不需要的 var,如果它们变重了。
The magic-commands resetand reset_selectiveis vailable on interactive python sessions like ipythonand Jupyter
魔术命令reset和reset_selective可用于交互式 python 会话,如 ipython和Jupyter
1) reset
1) reset
resetResets the namespace by removing all names defined by the user, if called without arguments.
reset如果不带参数调用,则通过删除用户定义的所有名称来重置命名空间。
inand the outparameters specify whether you want to flush the in/out caches. The directory history is flushed with the dhistparameter.
in和out参数指定是否要刷新输入/输出缓存。目录历史用dhist参数刷新。
reset in out
Another interesting one is arraythat only removes numpy Arrays:
另一个有趣的是array只删除 numpy 数组:
reset array
2) reset_selective
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']
Source: http://ipython.readthedocs.io/en/stable/interactive/magics.html
来源:http: //ipython.readthedocs.io/en/stable/interactive/magics.html
回答by Fardin
You can use python garbage collector:
您可以使用 python 垃圾收集器:
import gc
gc.collect()
回答by Viswa
This worked for me.
这对我有用。
You need to run it twice once for globals followed by locals
您需要为全局变量运行两次,然后是本地变量
for name in dir():
if not name.startswith('_'):
del globals()[name]
for name in dir():
if not name.startswith('_'):
del locals()[name]

