Python MacOS终端:原始输入()中的键盘箭头键

2024-06-16 14:38:33 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Python 2.7,我希望我的程序能够接受键盘箭头键–例如输入MacOS终端时

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

但是,按raw_input()提示符处的kbd>和返回值,似乎不会产生一个可以调节的字符串:

string = raw_input('Press ↑ Key: ')

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

如何做到这一点

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


Tags: 字符串程序终端inputstringraw序列macos
2条回答

当我试着做类似的事情时:

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

它将print语句中的“\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!"

我认为您正在寻找pynput.keyboard.Listener,它允许您monitor the keyboard并根据按下的键采取不同的操作。它适用于Python2.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()

相关问题 更多 >