Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there any way to detect key press in Python?

I am wanting to make a program with different responses when you press a key. Is there any way that you can detect a key press in Python?

The program is like when you press 0, it will say you pressed 0 and when you pressed ctrl-c it will say that you interrupted the program, so on.

Can you do this in a while True: loop as well?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Also, I don’t want it to be like input and I am using Linux (I don’t want to have to use root).

>Solution :

Assuming you want a command line application
you should be able to do it with

import sys
import termios
import tty
custom_messages = {'a': 'some other message'}
custom_messages['b'] = 'what?';
stdin = sys.stdin.fileno()
tattr = termios.tcgetattr(stdin)
try:
    tty.setcbreak(stdin, termios.TCSANOW)
    while True:
        char = sys.stdin.read(1)
        print(custom_messages.get(char, 'You pressed ' + char))
except KeyboardInterrupt:
  print('You interrupted')
  sys.exit() ## ?
finally:
    termios.tcsetattr(stdin, termios.TCSANOW, tattr)

I based my answer on disabling buffering in stdin

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading