0

I've been trying to find a good limited-input-time code for Python scripts and I finally got a code to work:

from threading import Timer

timeout = 5
t = Timer(timeout, print, ["Time's up!"])
t.start()
entry = input('> ')
t.cancel()

but, I need to be able to run a function when the timer ends. Also - I want the function called inside of the timer code - otherwise if you type your entry before the timer runs out, the function will still be called no matter what. Could anyone kindly edit this code I have to be able to run a function when the timer ends?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 3
    Hint: `print` is a function, can you replace `print` with something? – ssp Dec 06 '20 at 12:41
  • Does this answer your question? [Keyboard input with timeout?](https://stackoverflow.com/questions/1335507/keyboard-input-with-timeout) – Tomerikoo Dec 06 '20 at 12:47

1 Answers1

1

If it is fine that you block the main thread when the user has not provided any answer, the above code that you have shared might work.

Otherwise you could use msvcrt in the following sense:

import msvcrt
import time

class TimeoutExpired(Exception):
    pass

def input_with_timeout(prompt, timeout, timer=time.monotonic):
    sys.stdout.write(prompt)
    sys.stdout.flush()
    endtime = timer() + timeout
    result = []
    while timer() < endtime:
        if msvcrt.kbhit():
            result.append(msvcrt.getwche()) #XXX can it block on multibyte characters?
            if result[-1] == '\n':   #XXX check what Windows returns here
                return ''.join(result[:-1])
        time.sleep(0.04) # just to yield to other processes/threads
    raise TimeoutExpired

The above code is compliant with Python3 and you will need to test it.

Reading from the Python Documentation https://docs.python.org/3/library/threading.html#timer-objects

I have come up with the following snippet which might work(Try running in your command line prompt)

from threading import Timer


def input_with_timeout(x):    

def time_up():
    answer= None
    print('time up...')

t = Timer(x,time_up) # x is amount of time in seconds
t.start()
try:
    answer = input("enter answer : ")
except Exception:
    print('pass\n')
    answer = None

if answer != True:   # it means if variable has something 
    t.cancel()       # time_up will not execute(so, no skip)

input_with_timeout(5) # try this for five seconds
aryashah2k
  • 638
  • 1
  • 4
  • 16