简体   繁体   English

清除 Python 中用户创建的变量

[英]Clearing user-created variables in Python

I am an absolute beginner in Python. I have been using R and Matlab for data analysis for quite some time.我是Python的绝对初学者。我已经使用R和Matlab进行数据分析已有一段时间了。 One of the great things about these languages (or tools) is that I could run clear all in Matlab or rm(list=ls()) in R to clear the variables I created.这些语言(或工具)的一大优点是我可以在 Matlab 中运行clear all或在 R 中运行rm(list=ls())来清除我创建的变量。 I could then continue to experiment with my snippet of code.然后我可以继续试验我的代码片段。

I am struggling to find such a solution in Python. I researched Is there a way to delete created variables, functions, etc from the memory of the interpreter?我正在努力在 Python 中找到这样的解决方案。我研究了是否有办法从解释器的 memory 中删除创建的变量、函数等? and found that there are two ways to accomplish what I am trying to do, but in reality they are not any close.发现有两种方法可以完成我想做的事情,但实际上它们并不接近。

First method:第一种方法:

%Reset

This command deletes all variables and imported setting in PyCharm to run interactive mode.此命令删除 PyCharm 中的所有变量和导入设置以运行交互模式。 That is, after running above command, I have to re-run也就是说,运行上面的命令后,我必须重新运行

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

This is very annoying.这很烦人。

Second Method:第二种方法:

Another suggested method is to write a for loop and ignore functions starting with __ .另一个建议的方法是编写一个for循环并忽略以__开头的函数。 This also doesn't work for the reasons above.由于上述原因,这也不起作用。 For instance, when I start my PyCharm, I run例如,当我启动 PyCharm 时,我运行

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

to ensure that I am able to run a bunch of commands together just as I would do in Matlab and R (In PyCharm, the keyboard shortcut is [Alt + Shift + E; This is called as Execute Selection in Console]).以确保我能够像在 Matlab 和 R 中那样同时运行一堆命令(在 PyCharm 中,键盘快捷键是 [Alt + Shift + E;这在控制台中称为执行选择])。 I have noticed that the for loop mentioned in that Stackoverflow thread deletes some of the variables created by running above two lines of code.我注意到那个 Stackoverflow 线程中提到的for循环删除了一些通过运行上面两行代码创建的变量。 This means that I won't be able to execute statements by selecting them at a time.这意味着我将无法通过一次选择它们来执行语句。 I would have to type them individually on the prompt, which is annoying.我将不得不在提示符下单独键入它们,这很烦人。 Another option would be to run above two lines of code every time I execute the for loop, which is annoying as well.另一种选择是每次执行for循环时都运行以上两行代码,这也很烦人。

As an aside, I did some research to understand what happens after running above two lines of code.顺便说一句,我做了一些研究以了解运行以上两行代码后会发生什么。 I ran dir() after running above two lines to get a list of all variables existing in my session.我在运行以上两行后运行了dir()以获取我的 session 中存在的所有变量的列表。

The list looks like this列表看起来像这样

Out[4]: 
['In',
 'InteractiveShell',
 'Out',
 '_',
 '_2',
 '__',
 '___', 
......(continued)
 'sys']

Is there any way, I can delete user-created variables without deleting above variables?有什么办法,我可以在不删除上述变量的情况下删除用户创建的变量? In effect, I want to replicate what rm(list=ls()) would do for me in R.实际上,我想复制rm(list=ls())在 R 中为我做的事情。

I see that there are a number of people who have asked this question outside StackOverflow such as https://github.com/spyder-ide/spyder/issues/2563 .我看到有很多人在 StackOverflow 之外问过这个问题,例如https://github.com/spyder-ide/spyder/issues/2563

Thanks for any help.谢谢你的帮助。 I am using PyCharm with the latest Conda distribution (3.6).我在最新的 Conda 发行版 (3.6) 中使用 PyCharm。

Try this:试试这个:

>>> x = 1
>>> x
1
>>> globals().clear()
>>> x
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    x
NameError: name 'x' is not defined

Note that the the docs don't actually say that you can safely modify the dictionary that globals() returns, nor that modifying this dictionary will have the effect you intend (or any effect at all).请注意,文档实际上并没有说您可以安全地修改globals()返回的字典,也没有修改此字典会产生您想要的效果(或根本没有任何效果)。 But if you're just doing it for convenience in the REPL, then if it works, it works.但是如果你只是为了 REPL 中的方便而这样做,那么如果它有效,它就有效。

If you wish to simply clear all variables you've defined in the console.. That is to undo everything your code has done and 'start fresh'..如果您希望简单地清除您在控制台中定义的所有变量.. 那就是撤消您的代码所做的一切并“重新开始”..

Type:类型:

exit

in the console在控制台中

In Spyder this simply clears the workspace of anything your code has done.在 Spyder 中,这只是清除您的代码所做的任何工作区。 The same effect as closing and restarting Anaconda, but without having to do so.与关闭和重新启动 Anaconda 的效果相同,但不必这样做。 Now you can run your code with a fresh workspace!现在您可以使用全新的工作区运行您的代码!

How about running the code in "Interactive mode" in VSC?如何在 VSC 中以“交互模式”运行代码? You can close the interactive window to erase all the value of the variables.您可以关闭交互式 window 以清除所有变量的值。

Using PyCharm 2021.3.3 (Community Edition) built March 16. 2022: There are two columns of buttons on the left of the console the bottom left one says "New Console" on hover. Pressing it gives a new console (duh) with no user variables.使用 PyCharm 2021.3.3(社区版)于 3 月 16 日构建。2022:控制台左侧有两列按钮,左下角的按钮在 hover 上显示“新控制台”。按下它会提供一个新控制台(duh),没有用户变量。

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

相关问题 将 SPSS 26 python 设置为 Anaconda 用户创建的环境 - Setting SPSS 26 python to an Anaconda user-created environment 如何列出模块所依赖的用户创建的python文件? - How to make a list of the user-created python files that a module depends on? 用户创建的记录字段 - User-created Record Fields 非用户创建表的Django模型 - Django models for non user-created tables 如何突出显示对对象方法和用户创建的函数的调用? (SublimeText,python) - How to highlight calls to object methods and user-created functions? (SublimeText, python) 从相关目录导入用户创建的Python模块和数据文件 - Importing user-created Python modules and data files from relative directories 如何删除“__main__”。 从 Python 中用户创建的异常类开始 - How to remove “__main__.” from the beginning of user-created exception classes in Python 在 Python 中,为什么 pandas.Series.between 函数在用户创建的函数中返回错误“'str' object has no attribute 'between'”? - In Python, why does pandas.Series.between function return error "'str' object has no attribute 'between'" in user-created function? 用户创建的模块的Py2app ImportError - Py2app ImportError for user-created module pyinstaller生成的exe可以访问用户创建的输入文件吗? - Can a pyinstaller generated exe access user-created input files?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM