Reputation: 21
In the msvcrt.getch() method, when I enter any value that isn't in the ascii table, I get '\xe0' all the time. I don't know what this means
>>>import msvcrt
>>>up_arrow = msvcrt.getch()
>>> # this is where I have inputed the up arrow
>>>print up_arrow
'\xe0'
>>>down_arrow = msvcrt.getch()
>>>
>>>print down_arrow
'\xe0'
Upvotes: 1
Views: 2454
Reputation: 365895
This is explained in the docs:
If the pressed key was a special function key, this will return '\000' or '\xe0'; the next call will return the keycode.
Under the covers, as you can see from the source, Python is just calling the MSVCRT function _getch
, which is sort of like the POSIX function getch
, but different in one key way:
When reading a function key or an arrow key, each function must be called twice; the first call returns 0 or 0xE0, and the second call returns the actual key code.
The historical reason for this goes back to DOS compatibility in Windows NT 3.x (or, rather, Turbo C for DOS compatibility in Microsoft C++ for Windows NT).
IIRC (and I've probably got a few of the details wrong…), the basic idea was this: You'd make a BIOS call to get hi and lo values for the keyboard, meaning every key had a 16-bit value. Turbo C, to make things easier, provided a nice call that would map keys to their character in the current (8-bit) codepage, so a
would give you back a single byte, 0x61
. But there wasn't enough room to map everything, so special keys like VK_UP
would be returned unmapped, across two separate calls, first the hi byte 0xE0
and then the lo byte 0x50
. Microsoft copied that from Borland to make it easier to port code to their compiler, and then to port code from DOS/Win3.1 to NT, and so that's what MSVCRT still does today, and Python is just wrapping the function that does that.
This answer gives some more details.
Of course on most Unix terminals, the up arrow also send a sequence of characters, usually the same as the cursor-up display control sequence for that character, typically ESC
, then [
, then A
. But people don't expect a single-character getch
-like function to return a single value for every key on Unix, so nobody gets confused.
Upvotes: 4