如何在python中用键盘按下来停止秒表?

2024-05-16 00:29:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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)

Tags: 代码importtrueiftimesyssec键盘
2条回答

当用户使用ctrl + c退出程序时,KeyboardInterrupt异常被抛出。您需要使用另一种方法来检测按键。This answer似乎有一个很好的跨平台类来检查stdin。在

编辑:我上面链接的答案需要用户按enter键,这样如果你在另一个线程中运行它就可以了。在

以下方法适用于任何按键,但仅适用于Windows。在

import msvcrt
# Time
import time
import sys
timeLoop = True
# Variables to keep track and display
Sec = 0
Min = 0
Hour = 0
# Begin Process
while 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")
        if msvcrt.kbhit():
            break
    except KeyboardInterrupt:
        break

编辑2:Found a library for kbhit that has cross-platform support。在下面的示例中,我将其保存在与kbhit.py相同的目录中,并在第1行导入它。在

^{pr2}$

使用第二个线程(https://en.wikipedia.org/wiki/Multithreading_(computer_architecture)How to use threading in Python?):

def quit_on_user_input():
    input = raw_input("Press any key to quit.")
    # thread will lock up and wait for user to input. That's why this is on a separate thread.
    sys.exit(0)

quit_thread = threading.Thread(target=quit_on_user_input, args=[])
quit_trhead.start()
# The rest of your code. quit_thread will run in the background and therefor won't lock up your main thread.

相关问题 更多 >