-1

I'm programming a function that requests the user for input, and I would like the function to automatically terminate if the user takes too long to enter the input.

For example, a simplified version of my code is of the following:

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

Right now the program will wait for the user to input the result before executing anything else and as stated above, I would like the program to automatically stop running if the user takes too long to input the answer.

I'd appreciate any help!

Rob
  • 14,746
  • 28
  • 47
  • 65
Echidna
  • 164
  • 11
  • 3
    Does this answer your question? [Timeout on a function call](https://stackoverflow.com/questions/492519/timeout-on-a-function-call) – lllrnr101 Jan 30 '21 at 09:23

2 Answers2

0

generally, a python script runs in a single thread. adding a counter means a new thread must add for counting purposes.[ because the process for previous input data must execute meanwhile. ] On the other hand, this causes to add synchronization to the code. [ code waits for the Input.]

So, if the time counting only uses if it is compulsory. Else, the best way to make your code as much as synchronized. you can implement that by using the simple if condition: [ if you have a separate function for taking inputs, this condition can be used as a parser]

if input() == '-1':
   exit()

so, you can terminate the process at any time by input -1. [ -1 can change according to use case.]

however, there are python libraries to your exact case.

nipun
  • 672
  • 5
  • 11
0

You have an option to use eitherselect or poll. poll will not work under windows. Here is the code using 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.")
PGS
  • 79
  • 3