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

放肆的年华 提交于 2019-12-07 07:42:56

问题


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)

回答1:


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)



回答2:


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.



来源:https://stackoverflow.com/questions/24308583/python3-curses-how-to-press-q-for-ending-program-immediately

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!