Search code examples
pythonpython-3.xncursescursespython-curses

Python3 + Curses: How to press "q" for ending program immediately?


When I run the following sample code and press just "q", it'll ends properly, but if I pressed any other characters "for instance many breaks and a lot of other characters" and then press "q" it'll not exit, how can I solve this?

import curses, time

def main(sc):
    sc.nodelay(1)

    while True:
        sc.addstr(1, 1, time.strftime("%H:%M:%S"))
        sc.refresh()

        if sc.getch() == ord('q'):
            break

        time.sleep(1)

if __name__=='__main__': curses.wrapper(main)

Solution

  • Pressing other keys cause time.sleep(1) call, you should wait n seconds (n = number of other key strokes).

    Removing time.sleep call will solve your problem.

    def main(sc):
        sc.nodelay(1)
    
        while True:
            sc.addstr(1, 1, time.strftime("%H:%M:%S"))
            sc.refresh()
    
            if sc.getch() == ord('q'):
                break
    
            #time.sleep(1) <------
    

    Alternative: call time.sleep conditionally (only when no key was pressed, getch returns -1 if no key was pressed in non-blocking mode):

    while True:
        sc.addstr(1, 1, time.strftime("%H:%M:%S"))
        sc.refresh()
    
        key = sc.getch()
        if key == ord('q'):
            break
        elif key < 0:
            time.sleep(1)