How can I use a threading timer to get a countdown while waiting for the user to get input and if it is out of time, the next question auto pops up? Is it possible for me to stop threading immediately? Like if the user input and it stop counting
如何在等待用户输入的同时使用线程计时器进行倒计时,如果超时,下一个问题将自动弹出?我可以立即停止穿线吗?例如,如果用户输入并停止计数
with open("question.txt", "r") as question_file:
questions = question_file.read().splitlines()
with open("choice.txt", "r") as choice_file:
choices = choice_file.read().splitlines()
for i in range(len(questions)):
print("Question:", questions[i])
print(choices[i])
guess = input("Enter answer: ").upper()
while guess not in ['A', 'B', 'C', 'D']:
guess = input("Invalid input. Enter answer (A, B, C, D): ").upper()
if guess == answers[i]: # Compare with the correct answer for the current question
score += 1
更多回答
优秀答案推荐
Not the cleanest approach since you might have to use global boolean variable input_entered
to keep track if the user entered an input. When creating a timer thread, you can end the timer thread with SIGINT which will raise KeyboardInterrupt
exception in the main thread which can then be catched and move on to the next question
这不是最干净的方法,因为如果用户输入输入,您可能必须使用全局布尔变量INPUT_ENTERED来跟踪。创建计时器线程时,可以使用SIGINT结束计时器线程,这将在主线程中引发KeyboardInterrupt异常,然后可以捕获该异常并继续下一个问题
from threading import Thread
import time
import signal
import os
input_entered = False
def timer(duration):
global input_entered
time_waited = 0
while (not input_entered) and (time_waited < duration):
time.sleep(1)
time_waited += 1
if not input_entered:
os.kill(os.getpid(), signal.SIGINT)
def main():
global input_entered
with open("question.txt", "r") as question_file:
questions = question_file.read().splitlines()
with open("choice.txt", "r") as choice_file:
choices = choice_file.read().splitlines()
# Sample answers
answers = ['B', 'C', 'D']
score = 0
duration = 5 # wait 5 seconds
for i in range(len(questions)):
print("Question:", questions[i])
print(choices[i])
input_entered = False
thread = Thread(target=timer, args=[duration])
thread.start()
try:
guess = input("Enter answer: ").upper()
while guess not in ['A', 'B', 'C', 'D']:
guess = input("Invalid input. Enter answer (A, B, C, D): ").upper()
if guess == answers[i]: # Compare with the correct answer for the current question
score += 1
input_entered = True
except KeyboardInterrupt:
print('Time\'s up!')
finally:
thread.join()
if __name__ == '__main__':
main()
更多回答
我是一名优秀的程序员,十分优秀!