【问题标题】:msvcrt.getch() returning b'a' instead of 'a'?msvcrt.getch() 返回 b'a' 而不是 'a'?
【发布时间】:2015-06-14 02:01:37
【问题描述】:

我有一个班级的以下代码:

class _Getch:
    def __init__(self):
        self.impl = _GetchWindows()
    def read_key(self): 
        return self.impl()

class _GetchWindows:
    def __init__(self):
        import msvcrt
    def __call__(self):
        import msvcrt
        return msvcrt.getch()

然后我有另一个导入 _Getch 的类。在这个其他类中,我尝试使用 _Getch 提供的 read_key 来做有条件的事情:

r = _Getch()
key = r.read_key()
print(key)

if key = 'a':
    #do things
elif key = 's':
    # do other things
else:
    continue

当我尝试输入 'a' 时,我希望 key 是 'a',但它却返回了 b'a'。因此,key 不会满足任何条件,并且总是会继续。为什么它返回 b'a'?我该怎么做才能让它返回“a”?

【问题讨论】:

    标签: python-3.x msvcrt getch


    【解决方案1】:

    根据documentationmsvcrt.getch()返回一个字节串

    因此,您需要对其使用bytes.decode() 方法将其转换为Unicode 字符串。 提示:如果你这样做,你应该查找你的环境encoding并使用它而不是默认的utf-8。或者你可以使用errors='replace'

    或者您可以更改代码以与b'a' 进行比较。

    注意:您的代码中存在语法错误;您应该在 if 语句中使用 ==(比较运算符)而不是 =(赋值)。

    【讨论】:

      【解决方案2】:

      一个简单的方法是在 getch() 之后链接解码调用:

      import msvcrt
      
      key = msvcrt.getch().decode('ASCII')
      
      # 'key' now contains the ASCII representation of the input suited for easy comparison
      if key == 'a':
          # do a thing
      elif key == 's':
          # do another thing
      

      reference answer

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-25
        • 1970-01-01
        • 2016-03-23
        相关资源
        最近更新 更多