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

时间:2022-10-30 10:51:06

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中的“clear”的东西:一个命令/函数,它从工作空间中删除所有变量,从系统内存中释放它们。在Python里有这样的东西吗?

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

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

5 个解决方案

#1


35  

The following sequence of commands does remove every name 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 for clause 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(控制变量)也是留下来(作为条款重新在每次通过),所以它可能是更好的名字_控制变量,例如,清楚地表明“特殊”(+,在交互式解释器,名字_是绑定每个完整表达式输入后提示,这个表达式的值,所以它不会逗留太久;-)。

Anyway, once you have determined exactly what it is you 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).

无论如何,一旦您确定了您想要做什么,就不难为这个目的定义一个函数,并将它放入您的启动文件(如果您只希望它在交互式会话中)或站点自定义文件(如果您希望它在每个脚本中)。

#2


37  

No, you are best off restarting the interpreter

不,你最好重新启动翻译

Ipython is an excellent replacement for the bundled interpreter and has the %reset command which usually works

Ipython是绑定解释器的优秀替代品,并且具有%reset命令,该命令通常是有效的

#3


22  

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

如果你写了一个函数,一旦你把所有的名字都放在里面,就会消失。

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

这个概念叫做命名空间,它非常好,它使它成为了Python的Zen:

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 -f means "force"; in other words, "don't ask me if I really want to delete all the variables, just do it.")

IPython的名称空间同样可以使用神奇的命令%reset -f来重置。(- f意味着“力”;换句话说,“不要问我是否真的想删除所有的变量,就这么做吧。”

#4


2  

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一样工作。

#5


1  

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

#1


35  

The following sequence of commands does remove every name 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 for clause 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(控制变量)也是留下来(作为条款重新在每次通过),所以它可能是更好的名字_控制变量,例如,清楚地表明“特殊”(+,在交互式解释器,名字_是绑定每个完整表达式输入后提示,这个表达式的值,所以它不会逗留太久;-)。

Anyway, once you have determined exactly what it is you 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).

无论如何,一旦您确定了您想要做什么,就不难为这个目的定义一个函数,并将它放入您的启动文件(如果您只希望它在交互式会话中)或站点自定义文件(如果您希望它在每个脚本中)。

#2


37  

No, you are best off restarting the interpreter

不,你最好重新启动翻译

Ipython is an excellent replacement for the bundled interpreter and has the %reset command which usually works

Ipython是绑定解释器的优秀替代品,并且具有%reset命令,该命令通常是有效的

#3


22  

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

如果你写了一个函数,一旦你把所有的名字都放在里面,就会消失。

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

这个概念叫做命名空间,它非常好,它使它成为了Python的Zen:

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 -f means "force"; in other words, "don't ask me if I really want to delete all the variables, just do it.")

IPython的名称空间同样可以使用神奇的命令%reset -f来重置。(- f意味着“力”;换句话说,“不要问我是否真的想删除所有的变量,就这么做吧。”

#4


2  

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一样工作。

#5


1  

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