0

I am creating a script which requires input But if the user didn't respond, the script will stop there forever.
Let say I have:

my_input = input('Y/N')

For that I think After 30 seconds if the user didn't respond, the option will be N.
Maybe It could be Done by Module Keboard But I have No Idea.
I also tried the Following Code:

import time #using A Module
t = time.time() + 60*0.50 #adding more time
while time.time() < t: # time is less than t cause we added more time in it
    my_input = input('Y/N') #taking answer

Hope you may help me.

  • 2
    I think you're going to want to use threading for this. – idjaw Jun 26 '17 at 22:24
  • @mini Your approach with time.time() doesn't work because input() is blocking, meaning it will halt there until there is input, so if the user doesn't provide input after t amount of time, the condition still hasn't been evaluated to break the loop. The loop will only break it its been longer than t and the user has input something since then – jacoblaw Jun 26 '17 at 22:28
  • 1
    You can use `signal.alarm`, but only in Unix. – cs95 Jun 26 '17 at 22:34
  • For the linked solution for Windows, bear in mind that `kbhit` and `getche` require a regular console window. They won't work if you're using a GUI console that reads from a pipe, socket, or some other file-like `sys.stdin`. – Eryk Sun Jun 26 '17 at 22:43
  • There is definitely a solution in both those duplicates that *will* work for you. Make sure you read them carefully. – idjaw Jun 26 '17 at 22:51
  • @idjaw This [_**Question**_](https://stackoverflow.com/questions/2933399/how-to-set-time-limit-on-raw-input) worked for me. –  Jun 26 '17 at 22:55
  • Now I am going to turn it into a module. –  Jun 26 '17 at 22:57
  • You can implement a more flexible solution for Windows Vista+ by having a timer call [`CancelSynchronousIo`](https://msdn.microsoft.com/en-us/library/aa363794) to cancel a blocking read. This will work for `stdin` that's coming from a file, pipe, or console. – Eryk Sun Jun 26 '17 at 23:02
  • @eryksun I have soved my problem. –  Jun 26 '17 at 23:04

0 Answers0