Search code examples
pythonkeypress

Python 3 pressed key detect


Is there a built-in support way to detect which key is pressed in Python 3?Without third-party libraries?

I searched in Google, most answers use external libraries. Is there way to do that using Pure python ?


Solution

  • I got some answer, i don't know all imported libraries are builtin python or not, but it worked perfectly

    #!/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)