【问题标题】:How to stop a stopwatch with a keyboard press in python?如何在python中通过键盘按下停止秒表?
【发布时间】:2017-07-26 17:37:12
【问题描述】:

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

【问题讨论】:

  • 不一定回答问题,但是为什么要定义两次timeloop,也不需要做while timeloop == True:,你可以做while timeloop:
  • 在这种情况下,由于从未使用过 timeloop 变量,它可能只是 while True:
  • 你使用的是 Python 2 还是 Python 3?

标签: python input time


【解决方案1】:

使用第二个线程(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.

【讨论】:

  • raw_input() 要求用户按回车键。
  • 谢谢!现在效果很好:)
  • 太棒了!那么请您将此标记为答案吗?
【解决方案2】:

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

编辑:我上面链接的答案需要用户按回车键,这样如果你在不同的线程中运行它就可以工作。

以下方法适用于任何按键,但仅适用于 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

【讨论】:

  • 这样做的问题是评估 kbhit 所花费的时间会导致计时器失效。计时器必须是一个完全独立的线程,否则它不会是真正的毫秒。取决于处理器的速度,我们不知道处理 kbhit 需要多长时间。尤其是对于像 Python 这样较慢的语言。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
  • 2021-11-27
  • 1970-01-01
相关资源
最近更新 更多