python(v2.7)中是否有关键侦听器

2024-09-27 09:23:42 发布

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

我需要做一些类似于下面的伪代码(键侦听器)

while (true)
{
    if('a' key pressed)
    {
        A(); // calling function A
    }
    else if('b' key pressed)
    {
        B();
    }
    else if('e' key pressed)
    {
        break;
    }
}

我使用“win.getkey()”尝试了这种程序,但似乎无法正常工作。如何用python编写正确的密钥侦听器(无第三方库)


Tags: key代码程序trueif密钥functionwin
1条回答
网友
1楼 · 发布于 2024-09-27 09:23:42

您可以尝试以下代码。它不包含第三方模块

代码:

import sys, tty, os, termios


def getkey():
    old_settings = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin.fileno())
    try:
        while True:
            b = os.read(sys.stdin.fileno(), 3).decode()
            if len(b) == 3:
                k = ord(b[2])
            else:
                k = ord(b)
            key_mapping = {
                127: 'backspace',
                10: 'return',
                32: 'space',
                9: 'tab',
                27: 'esc',
                65: 'up',
                66: 'down',
                67: 'right',
                68: 'left'
            }
            return key_mapping.get(k, chr(k))
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)


try:
    while True:
        k = getkey()
        print("Detected key: {}".format(k))
        if k == 'esc':
            quit()
        else:
            print(k)
except (KeyboardInterrupt, SystemExit):
    os.system('stty sane')
    print('stopping.')

测试和输出:

>>> python3 test.py 
Detected key: a
a
Detected key: s
s
Detected key: d
d
Detected key: f
f
Detected key: right
right
Detected key: left
left
Detected key: space
space
Detected key: tab
tab
stopping.

注意:如果您能够使用外部Python模块,我建议使用pynputkeyboardPython模块。链接:https://github.com/boppreh/keyboardhttps://github.com/moses-palmer/pynput

相关问题 更多 >

    热门问题