Python get arrow keys from command line

I have a script that needs to interact with the user of the input (arrow keys pressed), but I cannot get the keys. I tried raw_input and some other functions but they didn't work. this is my example code of how it should look (triggering bool can be set to False in another function)

running = True
while running:
    #if input == Arrow_UP:
    #    do_Sth
    #elif ...
    display()
    time.sleep(1)

      

Another question: how can I call the display function only once per second, but react immediately to the input?

+3


source to share


1 answer


There are different situations:

  • If you are using a GUI like TKinter or PyGame , you can bind an event to an arrow key and wait for that event.

    An example in Tkinter, taken from this answer :

    from Tkinter import *
    
    main = Tk()
    
    def leftKey(event):
        print "Left key pressed"
    
    def rightKey(event):
        print "Right key pressed"
    
    frame = Frame(main, width=100, height=100)
    main.bind('<Left>', leftKey)
    main.bind('<Right>', rightKey)
    frame.pack()
    main.mainloop()
    
          

  • If your application stays in the terminal, consider using curses as described in this answer

    Curses is for creating interfaces that run in a terminal (under Linux).

  • If you use curses, the contents of the terminal will be cleared when the application is entered and restored after the application exits. If you don't want this behavior, you can use the getch () wrapper as described in this answer . After initializing getch with, getch = _Getch()

    you can save the next input usingkey = getch()

How to call display () every second, again depends on the situation, but if you are running the same process in the terminal, the process will not be able to call display () while it is waiting for input. The solution is to use a different thread for the display () function as in



import threading;

def display (): 
    threading.Timer(1., display).start ();
    print "display"

display ()

      

Here display

plans every second in the future every time you call. You can, of course, set some conditions around this call so that the process stops when some conditions are met, in your case when input was given. For details see.

+3


source







All Articles