【问题标题】:Terminate loop after a certain amount of time一定时间后终止循环
【发布时间】:2021-11-09 02:26:21
【问题描述】:

我正在尝试编写一个程序来测量用户的打字速度,但是我无法让用户输入的循环在时间到时终止。我希望在时间结束后立即停止循环。

from datetime import datetime, timedelta
text = 'Hello My name is matthew'

def some_function(duration):
    end_time = datetime.now() + timedelta(seconds=duration)
    while datetime.now() < end_time:
       answer = input('Type the following: ' + text + '\n\n')

duration = int(input('How long do you want to test yourself: '))

some_function(duration)

【问题讨论】:

  • this 回答你的问题了吗?

标签: python timer


【解决方案1】:

问题是input() 被阻塞了。在用户通过按 Enter 提交输入之前,不会执行其余代码。你应该看看这个thread for non-blocking console input

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 2014-01-17
    • 2017-08-12
    相关资源
    最近更新 更多