Skip to content Skip to sidebar Skip to footer

How To Set A Timeout For Input

If you wait out the 4 seconds it says 'You ran out of time' which is good. But then, to keep the loop going, you will have to press the enter key to continue. I want so that when

Solution 1:

Doing the task you proposed isn't as easy as you might've guessed. It is easier to use the signal module to do this: (I have incorporated your code with a modified version of the answer I linked)

import signal, time

defTimedInput(prompt='', timeout=20, timeoutmsg = None):
    deftimeout_error(*_):
        raise TimeoutError
    signal.signal(signal.SIGALRM, timeout_error)
    signal.alarm(timeout)
    try:
        answer = input(prompt)
        signal.alarm(0)
        return answer
    except TimeoutError:   
        if timeoutmsg:
            print(timeoutmsg)
        signal.signal(signal.SIGALRM, signal.SIG_IGN)
        returnNone

monsterhp = int(800)
y = 150while monsterhp > 0:
    timeout = 4
    timeoutmsg = 'You ran out of time.'print(" ")
    prompt = "You have %d seconds Type 'attack' to hit the monster\nType here: " % timeout
    answer = TimedInput(prompt, timeout, timeoutmsg)

    if answer == "attack":
        print("You strike the monster")
        time.sleep(1)
        monsterhp = monsterhp - y
        print("War Lord Health:", monsterhp)

Note: this will only work on all unix/mac system

You can change your while loop to this, for a improved version of your code:)

while monsterhp > 0:
        timeout = 4
        timeoutmsg = 'You ran out of time.'print(" ")
        prompt = "You have %d seconds Type 'attack' to hit the monster\nType here: " % timeout
        answer = TimedInput(prompt, timeout, timeoutmsg)

        if answer == "attack":
            print("You strike the monster")
            time.sleep(1)
            monsterhp = monsterhp - y
            print("War Lord Health:", monsterhp)
        elif answer == None:
            print("The War Lord has killed you, you're now dead")
            print("Thanks for playing, \nGAME OVER")
            break

Solution 2:

There is a new library inputimeout for standard input with timeout

$ pip install inputimeout

usage

from inputimeout import inputimeout, TimeoutOccurred
try:
    string = inputimeout(prompt='>>', timeout=5)
except TimeoutOccurred:
    string = 'time is over'print(string)

Post a Comment for "How To Set A Timeout For Input"