Python中的定时用户输入



我试图在Python中使用计时器获取用户输入。我希望用户只有10秒的时间来输入一些东西。然而,当10秒过后,提示"时间到了!"被打印,但是脚本不停止。

import pygame
from threading import Thread
clock = pygame.time.Clock()
timee = 0
UIn=None
def func1():
global timee
global clock
global UIn
while True:
milli = clock.tick()
seconds = milli/1000
timee=timee+seconds
if(int(timee)==10):
print("Time is over")
quit()

def func2():
global UIn
print("Working")
input("Press key:t")

Thread(target=func1).start()
Thread(target=func2).start()
UIn=input("Press key:t")

您可以使用Timer类来实现此目的

from threading import Timer
timeout = 10
t = Timer(timeout, print, ['Sorry, times up!'])
t.start()
prompt = "You have %d seconds to answer the question. What color do cherries have?...n" % timeout
answer = input(prompt)
t.cancel()

输出:

You have 10 seconds to answer the question. What color do cherries have?
(After 10 seconds)
Sorry, times up!

经过一番思考和感谢@Rabbid76,你可能想要这样的东西(修改后的代码从这个伟大的帖子):

import msvcrt
import time
import sys
class TimeoutExpired(Exception):
pass
def input_with_timeout(prompt, timeout, timer=time.monotonic):
"""Timed input function, taken from https://stackoverflow.com/a/15533404/12892026"""
sys.stdout.write(prompt)
sys.stdout.flush()
endtime = timer() + timeout
result = []
while timer() < endtime:
if msvcrt.kbhit():
result.append(msvcrt.getwche()) #XXX can it block on multibyte characters?
if result[-1] == 'r':
return ''.join(result[:-1])
time.sleep(0.04) # just to yield to other processes/threads
raise TimeoutExpired
# create a timed input object
try:
answer = input_with_timeout("Give me an answer: ", 10)
except TimeoutExpired:
print('nSorry, times up')
else:
print(f'nYour answer was: {answer}')
# continue with code and verify the input
if answer:
if answer == "yes":
print("OK")

最新更新