我试图弄清楚如何使python在一定时间后停止接受输入。
到目前为止,我的工作正常,但是直到用户按Enter才停止程序。如果有问题,我将在Anaconda提示符下运行此文件。
#I've made everything short so it's simpler
def f():
try:
if a != "Accepted word":
timer.cancel
print("...")
quit()
except NameError:
#This makes the code run anyway since if the user inputs nothing
#'a' will still be undefined and python will still be waiting for an input
timer.cancel
print("...")
if a == "":
quit()
#Like I said, Python won't actually stop until an input is made
else:
#This runs fine if the user inputs the 'accepted word'
timer.cancel
print(...)
quit()
timer = threading.Timer(5.0, f)
timer.start()
a = input(">")
换句话说,我想做些什么,以便Python停止等待输入。如果用户在计时器结束之前输入了任何内容,则程序可以正常运行,这很好,除非播放器没有输入任何内容。如果他们甚至没有按Enter键,那么整个过程将停止。 (我也是Python的绝对初学者。实际上,仅仅学习如何制作计时器并使用time.sleep函数花了我几个小时)(顺便说一下,这也是我所了解的程度)< / p>
答案 0 :(得分:0)
只需使用time.sleep()
sleep方法使python程序冻结一定时间(以毫秒为单位)。
因此,如果您想在特定时间内停止input()
,则可以这样做,
from time import sleep
sleep(1000) #stops the program for 1 seconds
s = input()
答案 1 :(得分:0)
您可以为此使用多线程。
from threading import Thread
import time
import os
answer = None
def ask():
global start_time, answer
start_time = time.time()
answer = input("Enter a number:\n")
time.sleep(0.001)
def timing():
time_limit = 5
while True:
time_taken = time.time() - start_time
if answer is not None:
print(f"You took {time_taken} seconds to enter a number.")
os._exit(1)
if time_taken > time_limit:
print("Time's up !!! \n"
f"You took {time_taken} seconds.")
os._exit(1)
time.sleep(0.001)
t1 = Thread(target=ask)
t2 = Thread(target=timing)
t1.start()
t2.start()