我正在寻找一个解决方案,以超时用户的输入后,一定的时间。 此代码应在5秒后打印“success…”,用户无需进行任何交互:
def input_with_timeout(timeout):
print ("Hello, you can type and press enter to change 'ans' variable value or wait "+str(timeout)+" seconds and the program will continue")
ans=input() #pass input after timeout
return ans
s="mustnotchange"
s=input_with_timeout(5)
if s=="mustnotchange":
print("Success, if you didn't just cheat by writing mustnotchange")
else:
print("you answered : "+s+" variable value has changed")
我知道这个问题经常被问到,但以下主题中提供的解决方案都不适用于Windows7和Python3(Windows7“ultimate”SP1 64位和Python3.6.8 64位) Python 3 Timed Input
How to set time limit on raw_input
实际上,我使用了一个“技巧”来避免这个问题:我用操作系统启动文件()但启动时无法对输入做出反应。你知道吗
如果没有任何有效的解决方法,那么一定很难做到这一点(多处理、线程、队列…),但这在很多情况下肯定会有所帮助。你知道吗
谢谢你。你知道吗
下面的代码用于跨平台提示
input()
一次 超时。超时时,它会要求用户按Enter键,以便提示器- 线程可以完全关闭。你知道吗删除影响
_prompter_exit
的部分将允许在超时时恢复,而无需用户按Enter键,代价是在整个进程退出之前保持提示线程的活动状态。你知道吗仅仅像@Mad physicast建议的那样加入一个超时提示线程是行不通的,因为它不会解除
input()
调用本身的阻塞。如果不使用特定于操作系统的库,那么如果不最终提供某种形式的输入,就无法唤醒等待input()
的线程。你知道吗代码是我答案的简化版本,允许在给定的时间跨度内进行多个输入:
Taking in multiple inputs for a fixed time in Python
用于演示:
运行触发超时:
使用用户输入及时运行:
最后我修改了@Darkonaut答案(谢谢!)为了匹配我的第一种情况,我在库
pynput
中添加了一个“模拟键盘”来自动按“回车”。你知道吗请注意,这在终端(python3.6.8和windows7sp1)中有效,但如果以IDLE启动则不起作用。你知道吗
相关问题 更多 >
编程相关推荐