如何清除 Python 脚本中间的所有变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3543833/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:39:35  来源:igfitidea点击:

How do I clear all variables in the middle of a Python script?

pythonclear

提问by snakile

I am looking for something similar to 'clear' in Matlab: A command/function which removes all variables from the workspace, releasing them from system memory. Is there such a thing in Python?

我在 Matlab 中寻找类似于“清除”的东西:一个命令/函数,它从工作区中删除所有变量,从系统内存中释放它们。Python中有这样的东西吗?

EDIT: I want to write a script which at some point clears all the variables.

编辑:我想编写一个脚本,在某些时候清除所有变量。

采纳答案by Alex Martelli

The following sequence of commands does remove everyname from the current module:

以下命令序列确实从当前模块中删除了每个名称:

>>> import sys
>>> sys.modules[__name__].__dict__.clear()

I doubt you actually DO want to do this, because "every name" includes all built-ins, so there's not much you can do after such a total wipe-out. Remember, in Python there is really no such thing as a "variable" -- there are objects, of many kinds (including modules, functions, class, numbers, strings, ...), and there are names, bound to objects; what the sequence does is remove every name from a module (the corresponding objects go away if and only if every reference to them has just been removed).

我怀疑您是否真的想要这样做,因为“每个名称”都包括所有内置插件,因此在彻底清除之后您无能为力。请记住,在 Python 中真的没有“变量”这样的东西——有很多类型的对象(包括模块、函数、类、数字、字符串等),还有绑定到对象的名称;序列所做的是从模块中删除每个名称(当且仅当对它们的每个引用都被删除时,相应的对象才会消失)。

Maybe you want to be more selective, but it's hard to guess exactly what you mean unless you want to be more specific. But, just to give an example:

也许您想要更有选择性,但除非您想更具体,否则很难准确猜测您的意思。但是,举个例子:

>>> import sys
>>> this = sys.modules[__name__]
>>> for n in dir():
...   if n[0]!='_': delattr(this, n)
... 
>>>

This sequence leaves alone names that are private or magical, including the __builtins__special name which houses all built-in names. So, built-ins still work -- for example:

这个序列只留下私有或魔法__builtins__名称,包括包含所有内置名称的特殊名称。因此,内置函数仍然有效——例如:

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'n']
>>> 

As you see, name n(the control variable in that for) also happens to stick around (as it's re-bound in the forclause every time through), so it might be better to name that control variable _, for example, to clearly show "it's special" (plus, in the interactive interpreter, name _is re-bound anyway after every complete expression entered at the prompt, to the value of that expression, so it won't stick around for long;-).

如您所见,名称n(其中的控制变量for)也恰好存在(因为它for每次都在子句中重新绑定),因此最好命名该控制变量_,例如,以清楚地显示“它是特殊”(另外,在交互式解释器中,_在提示符处输入每个完整表达式后,名称无论如何都会重新绑定到该表达式的值,因此它不会停留很长时间;-)。

Anyway, once you have determined exactly what it isyou want to do, it's not hard to define a function for the purpose and put it in your start-up file (if you want it only in interactive sessions) or site-customize file (if you want it in every script).

无论如何,一旦你已经确定到底是什么你想做的事,这不是很难定义的功能为目的,并把它放在你的启动文件(如果你只在互动环节希望它)或网站-自定义文件(如果你想在每个脚本中使用它)。

回答by John La Rooy

No, you are best off restarting the interpreter

不,你最好重启解释器

IPythonis an excellent replacement for the bundled interpreter and has the %resetcommand which usually works

IPython是捆绑解释器的绝佳替代品,并且具有%reset通常有效的命令

回答by Jochen Ritzel

If you write a function then once you leave it all names inside disappear.

如果你写了一个函数,一旦你离开它,里面的所有名字都会消失。

The concept is called namespaceand it's so good, it made it into the Zen of Python:

这个概念被称为命名空间,它非常好,它进入了Python禅宗

Namespaces are one honking great idea -- let's do more of those!

命名空间是一个很棒的想法——让我们做更多的事情!

The namespace of IPython can likewise be reset with the magic command %reset -f. (The -fmeans "force"; in other words, "don't ask me if I really want to delete all the variables, just do it.")

IPython 的命名空间同样可以使用魔法命令重置%reset -f。(-f意思是“强制”;换句话说,“不要问我是否真的要删除所有变量,就去做吧。”)

回答by Jug

This is a modified version of Alex's answer. We can save the state of a module's namespace and restore it by using the following 2 methods...

这是亚历克斯答案的修改版本。我们可以使用以下两种方法保存模块命名空间的状态并恢复它...

__saved_context__ = {}

def saveContext():
    import sys
    __saved_context__.update(sys.modules[__name__].__dict__)

def restoreContext():
    import sys
    names = sys.modules[__name__].__dict__.keys()
    for n in names:
        if n not in __saved_context__:
            del sys.modules[__name__].__dict__[n]

saveContext()

hello = 'hi there'
print hello             # prints "hi there" on stdout

restoreContext()

print hello             # throws an exception

You can also add a line "clear = restoreContext" before calling saveContext() and clear() will work like matlab's clear.

您还可以在调用 saveContext() 之前添加一行“clear = restoreContext”,并且 clear() 将像 matlab 的 clear 一样工作。

回答by Anurag Gupta

from IPython import get_ipython;   
get_ipython().magic('reset -sf')

回答by tardis

In Spyder one can configure the IPython console for each Python file to clear all variables before each execution in the Menu Run -> Configuration -> General settings -> Remove all variables before execution.

在 Spyder 中,可以为每个 Python 文件配置 IPython 控制台,以在 Menu 中的每次执行之前清除所有变量Run -> Configuration -> General settings -> Remove all variables before execution

回答by Harold Henson

In the idle IDE there is Shell/Restart Shell. Cntrl-F6 will do it.

在空闲的 IDE 中有 Shell/Restart Shell。Ctrl-F6 会做到。

回答by Kolay.Ne

The globals()function returns a dictionary, where keys are names of objects you can name (and values, by the way, are ids of these objects) The exec()function takes a string and executes it as if you just type it in a python console. So, the code is

globals()函数返回一个字典,其中键是您可以命名的对象的名称(顺便说一下,值是id这些对象的 s)该exec()函数接受一个字符串并执行它,就像您只是在 python 控制台中键入它一样。所以,代码是

for i in list(globals().keys()):
    if(i[0] != '_'):
        exec('del {}'.format(i))

回答by Ivan

Isn't the easiest way to create a class contining all the needed variables? Then you have one object with all curretn variables, and if you need you can overwrite this variable?

创建包含所有需要的变量的类不是最简单的方法吗?那么你有一个包含所有当前变量的对象,如果你需要你可以覆盖这个变量吗?