【问题标题】:"ESC" key to break loop by changing variable to False in Visual Studio“ESC”键通过在 Visual Studio 中将变量更改为 False 来中断循环
【发布时间】:2020-02-05 23:40:24
【问题描述】:

我在 Visual Studio Code 中有 2 个文件。 “ma​​in.py”和“g_Global.py”。 “g_Global.py”有这个代码:

import msvcrt

def key():
  if msvcrt.kbhit() and msvcrt.getch() == chr(27).encode():
    u = False

在“ma​​in.py”中有:

import g_Global as g

while x.lower() == 'n' and u == True:
  g.clear()
  print(y)
  y = input('Write a line to add. > ')
  g.key()
  if u == False:
    break

...但是当我运行代码时,当我按下“esc”时什么也没有发生。有什么想法吗?

【问题讨论】:

  • 这还能运行吗?文件 main 中的代码没有定义 u。编辑:猜猜这对你来说可能是一个剧透警报,如果你是细心的。您的错误是假设gGlobal.py 中的key 函数中的局部变量u 与main.py 中的变量u 有任何关系。就因为他们名字一样?不,那不行,它们在不同的命名空间中。
  • @ParitoshSingh u 已定义,每个文件大约有几千行代码,所以我没有费心包括整个 thingymajig

标签: python python-3.x escaping text-editor msvcrt


【解决方案1】:

当您从key() 访问u 时,u 是一个局部变量。您必须在开头添加global u 才能访问全局变量。即使这样,一个源文件中的变量不能从另一个源文件修改。您必须合并两个源文件(将key() 移动到另一个源文件)。

此外,虽然我熟悉msvcrt,但文档中说getchr 会阻塞,直到有要读取的密钥。所以也许只是摆脱input()kbhit()?不过,它可能不会在转义时出现,因为它是一个特殊的键。

示例:(我无法测试,因为我不在 MSVC 上)

import msvcrt

while u:
  if msvcrt.getch() == chr(27).encode():
     u = False

【讨论】:

    猜你喜欢
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 2021-12-15
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    相关资源
    最近更新 更多