4

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)
M. Adel
  • 401
  • 5
  • 7

2 Answers2

6

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)
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Many thanks @falsetru for you prompt reply, but as I mentioned it's a sample code, my real code is a top-like app with timeout/refresh-time option, so I must use sleep inside the code to match the defined timeout. – M. Adel Jun 19 '14 at 14:15
  • 1
    @M.Adel, How about calling `time.sleep` conditionally? (only when no key was pressed: `sc.getch()` returns `-1`) http://pastebin.com/JZgi9ewb – falsetru Jun 19 '14 at 14:27
  • @falsetru Excellent!! please paste it as answer to allow me to accept it, and many thanks guys for your help. – M. Adel Jun 19 '14 at 14:35
0

The function window.timeout(delay) is most likely what you are looking for. Once a timeout is set, getch will wait delay milliseconds before returning -1.

Although using time.sleep(seconds) will work, timeout is much cleaner and will give a smoother user experience due to sleep delaying the processing of user input by as much as seconds.

Tom Gangemi
  • 227
  • 2
  • 11