简体   繁体   English

python 使用 locals() 或 globals() 时意外退出

[英]python quits unexpectedly when using locals() or globals()

In a project that I was working on, I needed to go in and out from the interpreter constantly and I got bored of the key combination ctrl+z+enter .在我从事的一个项目中,我需要不断地从解释器中输入和输出 go,我对组合键ctrl+z+enter感到厌烦。 So I created a shortcut to exit faster from the python terminal with just two keys (from cmd), but it causes the interpreter to quit.因此,我创建了一个快捷方式,以便仅使用两个键(来自 cmd)从 python 终端更快地退出,但它会导致解释器退出。 Consider the following code inside of the file lazy.py :考虑文件lazy.py中的以下代码:

class hotkey():
     def __repr__(self):
          exit()
          return ''

q = hotkey()

The problem arises when I use from lazy import * and then try to use either locals() or globals() .当我使用from lazy import *然后尝试使用locals()globals()时,问题就出现了。 But if q is not directly in the scope, eg using import lazy , both of them work as expected, but the point of the module was to be able to just using q+enter and not lazy.q+enter .但是如果q不直接在 scope 中,例如使用import lazy ,它们都按预期工作,但模块的重点是能够只使用q+enter而不是lazy.q+enter

I gave up and returned to ctrl+z but not knowing the reason for this is subtracting my hours of sleep.我放弃并返回到ctrl+z但不知道这样做的原因是减少了我的睡眠时间。 Any idea of what could be going on?知道会发生什么吗?

You should be able to figure this out.你应该能够弄清楚这一点。 Try printing globals() without your import.尝试在不导入的情况下打印globals() Notice that each variable is listed along with its representation.请注意,每个变量都与其表示形式一起列出。 When it tries to fetch the representation for q , your code will exit the interpreter.当它尝试获取q的表示时,您的代码将退出解释器。

You must be on Windows. Remember that you can keep a separate console open with your interpreter;您必须拨打 Windows。请记住,您可以为您的口译员打开一个单独的控制台; you don't have to exit.你不必退出。 Also, if you pip install readline , then Ctrl-D and Ctrl-Z will exit the interpreter without the Enter.此外,如果您pip install readline ,则 Ctrl-D 和 Ctrl-Z 将在没有 Enter 的情况下退出解释器。

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

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