python - 如何在 10 秒后强制用户输入

标签 python python-3.x timer

我是 Python 新手,需要一些像游戏这样的测验帮助。 这是我的代码:

import time
from threading import Timer
import random as rnd

q = ["q1", "q2", "q3"]
a = ["a1    b1    c1", "a2    b2    c2", "a3    b3    c3"]
ca = ["b", "c", "b"]
points = 0


rand_q = rnd.randint(0, len(q) - 1)                                             # Choosing random question
print(q[rand_q] + "\n" + a[rand_q] + "\n")                                      # Asking question and showing answers
time.sleep(0.5)                                                                 # Little pause between prompts

t = Timer(10, print, ['Time is up!'])                                           # Setting up timer
t.start()                                                                       # Start timer
start = time.time()                                                             # Start of time check
answer = input("You have 10 seconds to choose the correct answer.\n")           # User input
if answer is ca[rand_q]:                                                        # Check if answer is correct
    print("Correct answer!")
    points = (points + round(10 - time.time() + start, 1)) * 10                 # Calculate points
else:
    print("Wrong answer!")
t.cancel()                                                                      # Stop timer
print("Points:", points)
input("Press ENTER to quit")

del q[rand_q]                                                                   # Removing the question
del a[rand_q]                                                                   # Removing the answer
del ca[rand_q]                                                                  # Removing the correct answer

当我运行这个程序时,我可以回答问题并获得分数,但每当我等待计时器结束时,我都会收到提示说时间到了,但我仍然可以填写并回答问题。

我希望输入在 10 秒后停止工作,但我似乎做不到。有什么方法可以使计时器在“时间已到”提示的顶部超时所有先前的输入。

我见过更多这样的帖子,但它们似乎已经过时,我没有让它们发挥作用。

编辑: sleep 命令不起作用。它会打印一行,说明为时已晚,但您仍然可以在之后输入答案。线程计时器也一样。我想在10秒后终止输入命令,但是windows好像没有解决办法。

最佳答案

问题是python的输入函数是阻塞的,这意味着下一行代码只有在用户输入一些数据后才会执行。非阻塞输入是很多人一直在要求的东西,但最好的解决方案是让您创建一个单独的线程并在那里提出问题。这个问题已经在 this 中得到了解答。发布

这个解决方案可以工作,除非用户在某些时候仍然需要按回车键才能继续:

import time
import threading

fail = False
def time_expired():
    print("Too slow!")
    fail = True

time = threading.Timer(10, time_expired)
time.start()
prompt = input("You have 10 seconds to choose the correct answer.\n")

if prompt != None and not fail:
    print("You answered the question in time!")
    time.cancel()

你可以做你想做的事,但它会变得非常复杂。

关于python - 如何在 10 秒后强制用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52368428/

相关文章:

python-3.x - 将高斯噪声添加到 float 据集并保存(python)

java - 从 3 个 Textview 获取值并转换为 int 用于倒计时器

python - Django、字符串编码、UTF-8 和问题 - AttributeError : 'Cursor' object has no attribute '_last_executed'

python - 使用 BeautifulSoup 获取 HTML 标签

python - re.findall() 查找所有包含否定项的二元组

python - 如何正确计算文本中带有变音符号的字母?

python - 如何在python中正确删除VBO?

html - BeautifulSoup - 在结果集上添加属性

c++ - 如何确保例程按时执行?

java - Android 中特定时间段的调用阻止