问题:有没有办法从解释器的内存中删除创建的变量,函数等?

我一直在寻找这个问题的准确答案已有几天了,但是还没有任何好的结果。我不是编程的完整初学者,但即使在中级水平上也还不是。

当我进入Python的外壳程序时,键入:dir()并且可以看到当前作用域(主块)中所有对象的所有名称,其中有6个:

['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']

然后,例如,当我声明一个变量时,x = 10它会自动添加到内置模块下的对象列表中dir(),当我dir()再次键入时,它现在显示:

['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'x']

函数,类等也是如此。

我如何删除所有这些新对象而不删除开始时可用的标准6?

我在这里已经阅读了有关“内存清理”,“控制台清理”的信息,该命令将删除命令提示符窗口中的所有文本:

>>> import sys
>>> clear = lambda: os.system('cls')
>>> clear()

但是,所有这些都与我要实现的目标无关,它不会清除所有使用过的对象。

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:

['__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:

['__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?

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.


回答 0

您可以使用以下方法删除个人名称del

del x

或者您可以将它们从globals()对象中删除:

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

这只是一个示例循环。它只在防御性上删除不以下划线开头的名称,并假设(并非毫无道理)您在解释器的开头仅使用了不带下划线的名称。如果您确实想透彻一点,则可以使用硬编码的名称列表来保留(白名单)。除了退出并重新启动解释器外,没有内置函数可以为您执行清除操作。

您已导入(import os)的模块将保持导入状态,因为它们被sys.modules; 引用。后续导入将重用已经导入的模块对象。您只是在当前的全局命名空间中没有对它们的引用。

You can delete individual names with del:

del x

or you can remove them from the globals() object:

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.


回答 1

是。有一种简单的方法可以删除iPython中的所有内容。在iPython控制台中,只需键入:

%reset

然后系统会要求您确认。按y。如果您不想看到此提示,只需键入:

%reset -f

这应该工作..

Yes. There is a simple way to remove everything in iPython. In iPython console, just type:

%reset

Then system will ask you to confirm. Press y. If you don’t want to see this prompt, simply type:

%reset -f

This should work..


回答 2

您可以使用python垃圾收集器:

import gc
gc.collect()

You can use python garbage collector:

import gc
gc.collect()

回答 3

如果您在的交互式环境中,Jupyter或者,如果您不想要的var变重,则ipython可能需要 清除它们。

magic命令resetreset_selective在交互式python会话(例如ipython和)上可用 Jupyter

1) reset

reset 通过删除用户定义的所有名称(如果不带参数调用)来重置命名空间。

inout参数指定是否要刷新输入/输出缓存。目录历史记录将使用dhist参数刷新。

reset in out

另一个有趣的是array,仅删除了numpy数组:

reset array

2)reset_selective

通过删除用户定义的名称来重置命名空间。输入/输出历史记录保留在您需要的时候。

清洁阵列示例:

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']

来源:http : //ipython.readthedocs.io/en/stable/interactive/magics.html

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

reset Resets 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

Another interesting one is array that only removes numpy Arrays:

reset array

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


回答 4

这对我有用。

您需要对全局变量运行两次,然后对本地变量运行

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

for name in dir():
    if not name.startswith('_'):
        del locals()[name]

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]

回答 5

实际上python会回收不再使用的内存。这被称为垃圾回收,这是python中的自动过程。但是,如果您仍然想这样做,则可以通过删除它del variable_name。您也可以通过将变量分配给None

a = 10
print a 

del a       
print a      ## throws an error here because it's been deleted already.

真正从未引用的Python对象回收内存的唯一方法是通过垃圾回收器。del关键字只是将对象的名称解除绑定,但是仍然需要对该对象进行垃圾回收。您可以强制垃圾收集器使用gc模块运行,但这几乎可以肯定是过早的优化,但是它有其自身的风险。使用del并没有真正的效果,因为这些名称会因为超出范围而被删除。

Actually python will reclaim the memory which is not in use anymore.This is called garbage collection which 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

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 del has no real effect, since those names would have been deleted as they went out of scope anyway.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。