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()
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
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?
According to the documentation,
msvcrt.getch()
returns a byte-string.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 defaultutf-8
. Or you can useerrors='replace'
.Or you can change your code to compare to
b'a'
instead.N.B.: There is a syntax error in your code; you should use
==
(a comparison operator) in yourif
statement instead of=
(assign).