You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python中getch()与ord()处理键盘输入:箭头键二次获取疑问

Understanding the Double 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 sometimes 0 for 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:

  1. When you press an arrow key, the first msvcrt.getch() returns the byte 224. You convert it to an integer with ord() and hit the elif key == 224: condition.
  2. 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:

  1. First getch() returns b'\xe0' (the byte equivalent of 224), ord() turns it into 224.
  2. The code enters the 224 branch, calls getch() again, which returns b'P' (byte equivalent of 80), ord() turns it into 80.
  3. 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

火山引擎 最新活动