msvcrt.getch() returning b'a' instead of 'a'?

4.1k views Asked by At

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?

2

There are 2 answers

0
Roland Smith On

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 default utf-8. Or you can use errors='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 your if statement instead of = (assign).

0
anhoppe On

A simple approach is to chain the decode call after 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

See reference answer