Python 设置特定函数的超时时间

Python 设置特定函数的超时时间,python,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 co

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

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

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脚本在单个线程中运行。添加计数器意味着必须添加新线程以进行计数。[因为之前输入数据的过程必须同时执行。] 另一方面,这会导致向代码中添加同步。[代码等待输入。]

因此,如果时间计数仅在强制的情况下使用。 否则,使代码尽可能同步的最佳方法。您可以通过使用简单的if条件来实现这一点:[如果您有一个单独的函数用于获取输入,那么这个条件可以用作解析器]

if input() == '-1':
   exit()
因此,您可以随时通过输入-1终止进程。[-1可以根据用例进行更改。]


但是,您也可以使用python库。

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