如何清除ipython中的变量?

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

How to clear variables in ipython?

pythonmemoryipython

提问by grasshopper

Sometimes I rerun a script within the same ipython session and I get bad surprises when variables haven't been cleared. How do I clear all variables? And is it possible to force this somehow every time I invoke the magic command %run?

有时我在同一个 ipython 会话中重新运行一个脚本,当变量没有被清除时,我会感到意外。如何清除所有变量?每次调用魔术命令 %run 时,是否可以以某种方式强制执行此操作?

Thanks

谢谢

采纳答案by aisbaa

%resetseems to clear defined variables.

%reset似乎清除了定义的变量。

回答by SeF

EDITED after @ErdemKAYA comment.

在@ErdemKAYA 评论后编辑。

To erase a variable, use the magic command:

要擦除变量,请使用魔术命令:

%reset_selective <regular_expression>

The variables that are erased from the namespace are the one matching the given <regular_expression>.

从命名空间中删除的变量是与给定的<regular_expression>.

Therefore

所以

%reset_selective -f a 

will erase allthe variables containing an a.

将删除所有包含a.

Instead, to erase only aand not aa:

相反,只擦除a而不是aa

In: a, aa = 1, 2
In: %reset_selective -f "^a$"
In: a  # raise NameError
In: aa  # returns 2

see as well %reset_selective?for more examples and https://regexone.com/for a regex tutorial.

%reset_selective?有关更多示例,请参见https://regexone.com/以获取正则表达式教程。

To erase all the variables in the namespace see:

要擦除命名空间中的所有变量,请参阅:

%reset?

回答by Carl

Adding the following lines to a new script will clear all variables each time you rerun the script:

每次重新运行脚本时,将以下行添加到新脚本中将清除所有变量:

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

To make life easy, you can add them to your default template.

为了让生活更轻松,您可以将它们添加到默认模板中。

In Spyder: Tools>Preferences>Editor>Edit template

在 Spyder 中: Tools>Preferences>Editor>Edit template

回答by Joop

In iPython you can remove a singlevariable like this:

在 iPython 中,您可以像这样删除单个变量:

del x

回答by Sirish

An quit option in the Console Panel will also clear all variables in variable explorer

控制台面板中的退出选项也将清除变量资源管理器中的所有变量

*** Note that you will be loosing all the code which you have run in Console Panel

*** 请注意,您将丢失在控制台面板中运行的所有代码

回答by Babu K.M.

I tried

我试过

%reset -f

and cleared all the variables and contents without prompt. -fdoes the force action on the given command without prompting for yes/no.

并在没有提示的情况下清除所有变量和内容。-f在不提示yes/no 的情况下对给定命令执行强制操作。

Wish this helps.. :)

希望这有帮助.. :)

回答by Devarshi Mandal

Apart from the methods mentioned earlier. You can also use the command del to remove multiple variables

除了前面提到的方法。也可以使用命令 del 删除多个变量

del variable1,variable2