Python中getch()与ord()处理键盘输入:箭头键二次获取疑问
msvcrt.getch() Call for Arrow Keys Great question! Let's break down exactly why that second msvcrt.getch() is required when handling arrow keys in your Windows CMD UI.
The Root Cause: How Windows Console Sends Special Key Inputs
On Windows, standard keys (like letters, numbers, ESC, or Enter) send a single byte when pressed. That's why your code works fine for ESC (byte 27) or Enter (byte 13) with just one getch() call.
But special keys like arrow keys, function keys (F1-F12), or modifier combinations don't work this way. Instead, the Windows console sends a two-byte escape sequence:
- The first byte is always
224(or sometimes0for other special keys) — this acts as a "signal" that the next byte will represent the actual special key. - The second byte is the unique identifier for the specific key (e.g., 80 for Down arrow, 72 for Up arrow).
How Your Code Handles This
Let's map this to your code step by step:
- When you press an arrow key, the first
msvcrt.getch()returns the byte224. You convert it to an integer withord()and hit theelif key == 224:condition. - The second
msvcrt.getch()call grabs the second byte of the escape sequence (like 80 for Down arrow). You convert this to an integer too, then check which arrow key it corresponds to.
If you didn't make that second call, you'd only have the 224 byte — which doesn't tell you which arrow key was pressed. That's why the code needs to wait for the second part of the sequence.
A Quick Example
Let's say you press the Down arrow:
- First
getch()returnsb'\xe0'(the byte equivalent of 224),ord()turns it into 224. - The code enters the
224branch, callsgetch()again, which returnsb'P'(byte equivalent of 80),ord()turns it into 80. - The code hits
elif key == 80:and prints "moveDown".
Bonus Note
Some other special keys use 0 as the first byte instead of 224 (like certain function keys). If you ever expand your UI to handle those, you'd need to add a check for key == 0 as well, followed by another getch() call to get the second byte.
内容的提问来源于stack exchange,提问作者077479




