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

时间:2017-07-26 17:37:13

标签: python input time

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

2 个答案:

答案 0 :(得分:3)

使用第二个帖子(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.

答案 1 :(得分:1)

当用户使用KeyboardInterrupt退出程序时,会引发ctrl + c异常。您将需要使用另一种方法来检测按键。 This answer似乎有一个很好的跨平台类来检查标准输入。

编辑:我上面链接的答案要求用户按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

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

from kbhit import KBHit
# Time
import time
import sys
timeLoop = True
# Variables to keep track and display
Sec = 0
Min = 0
Hour = 0

k = KBHit()
# 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 k.kbhit():
            break
    except KeyboardInterrupt:
        break