我用python做了一个超级简陋的秒表,只是为了让自己更好地适应它(这是我的第一种编程语言),我一直试图让代码在按下某个键时停止运行(使用键盘中断),但代码基本上忽略了键盘中断,一直持续下去。 (这是我的代码供参考)
# Time
import time
import sys
timeLoop = True
# Variables to keep track and display
Sec = 0
Min = 0
Hour = 0
# Begin Process
timeloop = True
while timeloop == True:
try:
Sec += 1
print(str(Hour) + " Hrs " + str(Min) + " Mins " + str(Sec) + " Sec ")
time.sleep(1)
if Sec == 60:
Sec = 0
Min += 1
print(str(Min) + " Minute")
if Min == 60:
Sec = 0
Min = 0
Hour += 1
print(str(Hour) + " Hours")
except keyboardInterrupt:
sys.exit(0)
当用户使用
ctrl + c
退出程序时,KeyboardInterrupt
异常被抛出。您需要使用另一种方法来检测按键。This answer似乎有一个很好的跨平台类来检查stdin。在编辑:我上面链接的答案需要用户按enter键,这样如果你在另一个线程中运行它就可以了。在
以下方法适用于任何按键,但仅适用于Windows。在
编辑2:Found a library for kbhit that has cross-platform support。在下面的示例中,我将其保存在与
^{pr2}$kbhit.py
相同的目录中,并在第1行导入它。在使用第二个线程(https://en.wikipedia.org/wiki/Multithreading_(computer_architecture),How to use threading in Python?):
相关问题 更多 >
编程相关推荐