Python3按键检测

Python3按键检测,python,keypress,Python,Keypress,是否有一种内置的支持方式来检测Python 3中按下了哪个键?而不使用第三方库 我在谷歌搜索,大多数答案都使用外部库。有没有办法使用纯python实现这一点?我得到了一些答案,我不知道所有导入的库是否都内置在python中,但它工作得非常好 #!/usr/bin/python3 # adapted from https://github.com/recantha/EduKit3-RC-Keyboard/blob/master/rc_keyboard.py import sys, termio

是否有一种内置的支持方式来检测Python 3中按下了哪个键?而不使用第三方库


我在谷歌搜索,大多数答案都使用外部库。有没有办法使用纯python实现这一点?

我得到了一些答案,我不知道所有导入的库是否都内置在python中,但它工作得非常好

#!/usr/bin/python3

# adapted from https://github.com/recantha/EduKit3-RC-Keyboard/blob/master/rc_keyboard.py

import sys, termios, tty, os, time

def getch():
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read(1)

    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch

button_delay = 0.2

while True:
    char = getch()

    if (char == "p"):
        print("Stop!")
        exit(0)

    if (char == "a"):
        print("Left pressed")
        time.sleep(button_delay)

    elif (char == "d"):
        print("Right pressed")
        time.sleep(button_delay)

    elif (char == "w"):
        print("Up pressed")
        time.sleep(button_delay)

    elif (char == "s"):
        print("Down pressed")
        time.sleep(button_delay)

    elif (char == "1"):
        print("Number 1 pressed")
        time.sleep(button_delay)

Windows还是Linux?简而言之:将C解决方案翻译成C类型请澄清,您到底想做什么。另外,您能否提供一个示例/data.Btw,请查看以下内容:对于Windows:这只适用于Unix:谢谢,是的,它只适用于Unix,但目前还可以:)