首页 > 解决方案 > 为特定功能设置超时时间

问题描述

我正在编写一个请求用户输入的函数,如果用户输入输入的时间过长,我希望该函数自动终止。

例如,我的代码的简化版本如下:

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

现在程序将在执行任何其他操作之前等待用户输入结果,如上所述,如果用户输入答案的时间过长,我希望程序自动停止运行。

我会很感激任何帮助!

标签: python

解决方案


您可以选择使用selectpollpoll在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.")

推荐阅读