简体   繁体   English

清除 IPython 中除少数特定变量外的所有内容

[英]Clear all except for a few specific variables in IPython

I'm aware of the %reset and %reset_selective commands in IPython .我知道IPython中的%reset%reset_selective命令。 However, let's say you have many variables and you want to clear all variables except x , y , z .但是,假设您有很多变量并且您想要清除除xyz之外的所有变量。 Is there a concise way to accomplish this?有没有一种简洁的方法来完成这个? Say a %reset_all_except x,y,z ?说一个%reset_all_except x,y,z

%reset_selective accepts RegEx. %reset_selective接受正则表达式。
If you have variables named as: glob_x, glob_y, glob_z which you don't want to reset, you can use: %reset_selective -f ^(?.glob_).*$如果你有变量命名为: glob_x, glob_y, glob_z你不想重置,你可以使用: %reset_selective -f ^(?.glob_).*$

this is a collective answer based off a ton of similar questions:这是基于大量类似问题的集体答案:

capture default variables in the system (should be your very first line of code):捕获系统中的默认变量(应该是你的第一行代码):

save_list = dir()

add other variables you want to save to the list before the "clear variables" command is used:在使用“清除变量”命令之前,将要保存的其他变量添加到列表中:

save_list.append(*your_variable_to_be_saved*)

finally, clear all variables (except default and saved) with:最后,使用以下命令清除所有变量(默认和保存除外):

for name in dir():
    if name not in save_list:
        del globals()[name]

for name in dir():
    if name not in save_list:
        del locals()[name]

this will clear all variables except the default and those you choose to save.这将清除除默认变量和您选择保存的变量之外的所有变量。 whenever i did that without saving default variables, it cleared those too and i had to restart kernel to get them back.每当我在没有保存默认变量的情况下这样做时,它也会清除这些变量,我必须重新启动内核才能将它们恢复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM