Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last key pressed in python?

First I want to say that I know that there is a solution with curses.
My programm is a while loop that is run every second. Every second I want to get the last key that was or is pressed. So in case you press a key while the loop sleeps I want that the key is saved so I can get the key that was pressed last even when it isnt pressed anymore. I dont want the saved key to be "deleted" after getting it. So when the user pressed the "a" key I want to get it every second until he pressed another key. If a specific key was pressed i want to print text. This text i want to write in a file using the redirection of stdout:

 ./test.py > file.txt

My python programm solved with curses looks like this:

import curses
from time import sleep

stdscr=curses.initscr()
stdscr.nodelay(1)
curses.noecho()
curses.cbreak()

while True:
    char=stdscr.getch()
    if char == 111:        #111 = "o" key
        print("test")
        break
    elif char == 97        #97 = "a" key

        #code that have to be run every second
        #if the a key is the last pressed key!

    sleep(1)

curses.nocbreak()
curses.echo()
curses.endwin()

The problem obout this solution is that curses gives me crazy output. I only press one time the "o" key and after the programm stopped file.txt looks like this:

^[[?1049h^[[1;30r^[(B^[[m^[[4l^[[?7h^[[H^[[2Jtest
^[[30;1H^[[?1049l^M^[[?1l^[>

But it should look like this:

test

I would be very greatful if someone writes an answer. I know that python isnt the best choice for programms using keypress events. But i have reasons why i use python for this.

Thank you very much in advance for your answers.

like image 738
timakro Avatar asked May 06 '14 18:05

timakro


1 Answers

You can install and use the getch package.

import getch
from time import sleep
while True:
    char = getch.getch()
    if char == 111:
        print("test")
        break
    sleep(1)

(you might need to use getch.getche instead of getch.getch. It's not completely clear from your question)

like image 77
shx2 Avatar answered Sep 29 '22 07:09

shx2