-2

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 ?

George Sovetov
  • 4,942
  • 5
  • 36
  • 57
C.V
  • 909
  • 2
  • 9
  • 20
  • Windows or Linux? In short: translate C solution to ctypes – RandomB Nov 28 '19 at 08:49
  • Could you please clarify, what exactly do you want to do. Also, can you provide a sample example/data. – Cool Breeze Nov 28 '19 at 08:49
  • Btw, pls look these: https://stackoverflow.com/questions/24072790/detect-key-press-in-python and for Windows: https://www.codespeedy.com/how-to-detect-which-key-is-pressed-in-python/ – RandomB Nov 28 '19 at 08:50

1 Answers1

1

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)
C.V
  • 909
  • 2
  • 9
  • 20
  • This will only work on Unix: ["Because it requires the termios module, it will work only on Unix."](https://docs.python.org/3/library/tty.html) – Lomtrur Nov 28 '19 at 09:08
  • Thanks, yes it's worked only unix, but it's fine for now :) – C.V Dec 12 '19 at 06:48