So, I want to make a program that execute associated part of code while and until the key on keyboard is pressed. I was looking for it long, long time and I didn't find anything. Can you please help me or just send something like a tutorial ? I want the program to do (for example) on "W" press do , on "S" press do .


There are many posts that address this. Here is a link to get you started.

Here is a python program that will do what you ask. VERY IMPORTANT - don't use more multiprocessing such as children of workers, queues, etc because the call to terminate will mess up garbage collection and will cause you problems over time.

import multiprocessing as mp
import time
import sys
import tty
import termios

def get_ch():
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
            ch = sys.stdin.read(1)
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

def worker():
    """ Do work """
    while True:

p = mp.Process(target=worker)

Hope this helps!

  • 1. I don't understand this code :/. 2. It doesn't work. I want the program to do (for example) on "W" press do <this>, on "S" press do <that>. – Nicolas Aug 13 '15 at 8:20
  • @Nicolas - you need to add details of what doesn't work etc, as well as what situation you want to use this in. For instance, is this to detect keys being pressed into the current TTY/terminal, or is it to be a background process that detects keyboard input? – Wilf Aug 13 '15 at 13:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.