Python MacOS 终端:raw_input() 中的键盘箭头键

Python MacOS Terminal: Keyboard Arrow keys in raw_input()

使用 Python 2.7,我希望我的程序能够接受键盘方向键——例如 正在输入 MacOS 终端。

在终端中按 输出 ^[[A,所以我假设这是转义键序列。

然而,在raw_input()提示符下按RETURN似乎没有产生然后可以调节的字符串:

string = raw_input('Press ↑ Key: ')

if string == '^[[A':
    print '↑'         # This doesn't happen.

如何做到这一点?

请注意,我并没有尝试输入 shell 中的任何前一行(我认为这是 import readline 管理的)。我只是想检测键盘上的箭头键是否以某种方式输入。

我认为您正在寻找 pynput.keyboard.Listener,它允许您 monitor the keyboard 并根据按下的键采取不同的操作。它适用于 Python 2.7。

这个例子是入门的好方法:

from pynput import keyboard

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False

# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

# ...or, in a non-blocking fashion:
listener = keyboard.Listener(
    on_press=on_press,
    on_release=on_release)
listener.start()

当我尝试类似的东西时:

% cat test.py
char = raw_input()
print("\nInput char is [%s]." % char)
% python a.py
^[[A
           ].

它删除了打印语句的“\Input char is [”部分。 raw_input() 似乎没有收到转义字符。终端程序正在捕获转义的击键并使用它来操纵屏幕。您将不得不使用较低级别的程序来捕获这些字符。 查看 Finding the Values of the Arrow Keys in Python: Why are they triples? 是否有关于如何获得这些击键的帮助。

从当前accepted answer开始:

    if k=='\x1b[A':
            print "up"
    elif k=='\x1b[B':
            print "down"
    elif k=='\x1b[C':
            print "right"
    elif k=='\x1b[D':
            print "left"
    else:
            print "not an arrow key!"