Python3 +诅咒:如何按"q"立即结束程序? [英] Python3 + Curses: How to press "q" for ending program immediately?
问题描述
当我运行以下示例代码并仅按"q"时,它将正确结束, 但是如果我按任何其他字符例如很多休息和许多其他字符",然后按"q",它不会退出,我该如何解决呢?
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)
推荐答案
按下其他键会导致time.sleep(1)
调用,您应该等待n
秒(n
=其他按键次数).
Pressing other keys cause time.sleep(1)
call, you should wait n
seconds (n
= number of other key strokes).
删除time.sleep
呼叫将解决您的问题.
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) <------
替代方法:有条件地调用time.sleep
(仅当未按下任何键时,如果在非阻塞模式下未按下任何键,则getch
返回-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)
这篇关于Python3 +诅咒:如何按"q"立即结束程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!