How to get the last key pressed in python?
Asked Answered
M

1

7

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.

Myatt answered 6/5, 2014 at 18:12 Comment(2)
If you wrote directly to your file instead of redirecting stdout - then you wouldn't have the "crazy output" from curses in your file...Hitormiss
I have some other programms writing in a .fifo and i always use the redirection. I want to keep this "format" that i can handle them easily.Myatt
S
3

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)

Spellman answered 6/5, 2014 at 18:23 Comment(2)
If you use getch you have to do: if char == "o"Myatt
I want code in the loop that runs every second and uses the key input.Myatt

© 2022 - 2024 — McMap. All rights reserved.