Emlingur
Emlingur

Reputation: 163

Getch gets input before it is called

I'm writing a curses application in python.

def main(stdscr):
    stuff(stdscr)

def printStuff(stdscr, string):
    stdscr.clear()
    stdscr.addstr(0, 0, string)
    stdscr.refresh()

def stuff(stdscr):
    printStuff(stdscr, 'foo')
    time.sleep(3)
    printStuff(stdscr, 'bar')
    stdscr.getch()

wrapper(main)

When I run the code, all is good, for the most part. If I press a button in the three second gap at the sleep, the getch will gladly take that as its input, even though the button was pressed before the getch was called. Why is that, and how can i fix this?

Upvotes: 0

Views: 245

Answers (1)

Barmar
Barmar

Reputation: 781058

Input is buffered, and getch() processes whatever is in the input buffer. You can clear the buffer with curses.flushinp

def stuff(stdscr):
    printStuff(stdscr, 'foo')
    time.sleep(3)
    printStuff(stdscr, 'bar')
    stdscr.flushinp()
    stdscr.getch()

Upvotes: 2

Related Questions