msvcrt.getch()返回b'a'而不是'a'? [英] msvcrt.getch() returning b'a' instead of 'a'?

查看:445
本文介绍了msvcrt.getch()返回b'a'而不是'a'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类的以下代码:

I have the following code from one class:

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在条件条件下执行操作:

And then I have another class that imported _Getch. Within this other class, I tried to use the read_key provided by _Getch to do things in the conditional:

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'.因此,密钥将不满足任何条件,并且将始终继续下去.为什么返回b'a'?我该怎么做才能使其返回"a"?

When I tried to input 'a', I was expecting key to be 'a', but it returned b'a' instead. Thus, key would not fulfill any of the conditionals, and would always go to continue. Why did it return b'a'? What can I do to make it return 'a' instead?

推荐答案

根据文档msvcrt.getch()返回字节字符串.

因此,您需要使用 bytes.decode() 将其转换为unicode字符串的方法. 提示:如果执行此操作,则应查找环境 encoding ,并使用其代替默认的utf-8.或者,您可以使用errors='replace'.

So you will need to use the bytes.decode() method on it to turn it into a unicode string. Hint: If you do this, you should look up your environments encoding and use that instead of the default utf-8. Or you can use errors='replace'.

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

Or you can change your code to compare to b'a' instead.

N.B.:您的代码中存在语法错误;您应该在if语句中使用==(比较运算符),而不是=(分配).

N.B.: There is a syntax error in your code; you should use == (a comparison operator) in your if statement instead of = (assign).

这篇关于msvcrt.getch()返回b'a'而不是'a'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆