问题:如何清除ipython中的变量?

有时,我会在同一ipython会话中重新运行脚本,但在未清除变量的情况下,我会感到很惊讶。如何清除所有变量?每次我调用魔术命令%run时是否有可能强制执行此操作?

谢谢

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?

Thanks


回答 0

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

%reset seems to clear defined variables.


回答 1

@ErdemKAYA评论后编辑。

要删除变量,请使用magic命令:

%reset_selective <regular_expression>

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

因此

%reset_selective -f a 

将删除所有包含的变量a

相反,仅擦除a而不是aa

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

另请参阅以%reset_selective?获取更多示例和https://regexone.com/获得regex教程。

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

%reset?

EDITED after @ErdemKAYA comment.

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>.

Therefore

%reset_selective -f a 

will erase all the variables containing an a.

Instead, to erase only a and not 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.

To erase all the variables in the namespace see:

%reset?

回答 2

在iPython中,您可以删除单个变量,如下所示:

del x

In iPython you can remove a single variable like this:

del x

回答 3

我试过了

%reset -f

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

希望这会有所帮助.. :)

I tried

%reset -f

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

Wish this helps.. :)


回答 4

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

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

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

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

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


回答 5

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

del variable1,variable2

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

del variable1,variable2

回答 6

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

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

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


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