'How can I stop the 'input()' function after a certain amount of time?

I'm trying to figure out how to make python stop accepting input after a certain amount of time.

What I've got so far works, but won't stop the program until the user presses Enter. If it matters, I'm running this file in the Anaconda prompt.

#I've made everything short so it's simpler
def f():
    try:
        if a != "Accepted word":
            timer.cancel
            print("...")
            quit()

    except NameError:
            #This makes the code run anyway since if the user inputs nothing 
            #'a' will still be undefined and python will still be waiting for an input
            timer.cancel
            print("...")
            if a == "":
            quit()
            #Like I said, Python won't actually stop until an input is made
    else:
        #This runs fine if the user inputs the 'accepted word'
        timer.cancel
        print(...)
        quit()
timer = threading.Timer(5.0, f)
timer.start()
a = input(">")

To put it in different words, I want to make something so that Python will stop waiting for an input. If the user inputs anything before the timer ends, the program runs fine, which is great, unless the player inputs nothing. If they don't even press Enter, then the whole process halts. (I'm also an absolute beginner in Python. In fact, just learning how to make a timer and use the time.sleep function took me a couple hours)(Which is also, by the way, the extent of my knowledge)



Solution 1:[1]

You could use Multi-threading for this.

from threading import Thread
import time
import os

answer = None


def ask():
    global start_time, answer
    start_time = time.time()
    answer = input("Enter a number:\n")
    time.sleep(0.001)


def timing():
    time_limit = 5
    while True:
        time_taken = time.time() - start_time
        if answer is not None:
            print(f"You took {time_taken} seconds to enter a number.")
            os._exit(1)
        if time_taken > time_limit:
            print("Time's up !!! \n"
                  f"You took {time_taken} seconds.")
            os._exit(1)
        time.sleep(0.001)


t1 = Thread(target=ask)
t2 = Thread(target=timing)
t1.start()
t2.start()

Solution 2:[2]

Just take the input in another process and after some time terminate the process.

import time, multiprocessing
def takeinput():
    stdin = open(0)
    print("give it up:", end = "", flush = 1)
    x = stdin.readline()
    print(x)
if __name__ == "__main__":
    process = multiprocessing.Process(target = takeinput)
    process.start()
    time.sleep(5)
    process.terminate()
    process.join()
    print("\nalright, times up!")

Hope this helps :D

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 suravshrestha
Solution 2