How to capture special keys for python console application
Question: Python 2.7

I'm trying to capture key presses in an application I'm writing using the
getch() function in the msvcrt module. Some are easy, enter is 13, backspace
is 8, .> is 46 etc. Some keys, such as Home, I can't work out.

From the docstring for getch():

"If the pressed key was a special function key, this will return ‘000’ or
‘xe0’; the next call will return the keycode."

I've tried testing for a return value of '000' or 'xe0' but this is not
returned. What happens is I get 224 returned and on the next call of getch() I
get another code, so for Home it's 71. Other special keys behave this way too,
End is 224 79, Insert is 224 82, Page Up is 224 73 etc. I can't explain this
behaviour; I've tried seeing if adding the two values together and then taking
off a power of two helps (i.e. 224 + 73 - 256) but it doesn't produce anything
useful.

Does anyone understand this behaviour and/or does anyone have any advice about
how to capture these keys (I didn't want to hard code the 224 + x pattern
values as I'm not confident these are consistent with other users)?

Thank you.

EDIT: code if anyone wants to try it out

    
    
    import msvcrt
    
    while True:
        key = msvcrt.getch()
        print ord(key)
    


Answer: The mentioned value returned by `getch()` is not `'xe0'`, it's **`'\xe0'`** \-
note the backslash indicating an [escape
sequence](http://legacy.python.org/dev/peps/pep-0223/). `224` is just the
decimal value of that byte:

    
    
    ord('\xe0') == 224
    

So in your case, this should work:

    
    
    while True:
        key = msvcrt.getch()
        if key in ('\000', '\xe0'):
            # special key, handle accordingly
            # ...
    

