python - 为特定功能设置超时时间
问题描述
我正在编写一个请求用户输入的函数,如果用户输入输入的时间过长,我希望该函数自动终止。
例如,我的代码的简化版本如下:
user_input = input('Please enter "yes" or "no" below: ')
if user_input.lower() == 'yes':
# executes some code
elif user_input.lower() == 'no':
# executes some code
else:
# executes some code
现在程序将在执行任何其他操作之前等待用户输入结果,如上所述,如果用户输入答案的时间过长,我希望程序自动停止运行。
我会很感激任何帮助!
解决方案
您可以选择使用select
或poll
。poll
在windows下将无法工作。这是使用的代码select()
import sys
import select
obj_check = [sys.stdin]
out_data = []
error_list = []
time_out = 5
print("Waiting for only 5 seconds for your input. Please enter yes or no:")
read_list, write_list, except_list = select.select( obj_check, out_data,error_list, time_out )
if (read_list):
myStr = sys.stdin.readline().strip()
if(myStr == 'yes'):
print("Received - Yes")
elif (myStr == 'no'):
print("Received - No")
else:
print("Bye")
else:
print("No Input Received.")
推荐阅读
- javascript - 将 SVG 文件保存到带有多个图像的 JavaScript 变量中,并引用每个图像并单独附加它们
- python - 将字符串和字符串列表合并到一个大列表中
- c# - 如何在c#中替换url中的主机名?
- asynchronous - Flutter FutureBuilder 逻辑
- javascript - 初始化后上传设置参数
- linux - 比较字符串和变量时出现奇怪的 Bash 错误
- html - Overflow-X 不显示滚动条
- html - HTML5“按ESC退出全屏”自定义消息
- java - 如何将对象数组从一种方法转移到另一种方法并返回一个新对象?
- ruby-on-rails - 无法写入未知属性“client_mutation_id”