Python 3.x msvcrt.getch()返回b';a';而不是';a';?

Python 3.x msvcrt.getch()返回b';a';而不是';a';?,python-3.x,msvcrt,getch,Python 3.x,Msvcrt,Getch,我从一个类中获得以下代码: 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 msv

我从一个类中获得以下代码:

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_键在条件

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

if key = 'a':
    #do things
elif key = 's':
    # do other things
else:
    continue
当我尝试输入“a”时,我希望键是“a”,但它返回了b“a”。因此,key不会满足任何条件,并且总是继续。为什么它返回b'a'?我该怎么做才能让它返回“a”?

根据,
msvcrt.getch()
返回一个字节字符串

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

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


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

一种简单的方法是在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