Ask coding questions

← Back to all posts
Python Input
LoneAce (221)

Hey there, I would like to give a timeout on my Python inputs. If possible, I would like the code to be portable so that I can give timeouts to everything else I do.

Please do not answer with the timeout decorator I rather not that since I tried it already

Thanks for those who help :)

Answered by Roar123 (446) [earned 5 cycles]
View Answer
Comments
hotnewtop
Roar123 (446)

This was my attempt to create a timed input function:

import time 

def timed_input(prompt,t):
    
    start = time.time()
    inp = input(prompt)
    now = time.time()

    if now - start < t:
        return inp
    else:
        return "Timed Out"

Edit: It works!
I thought the code for input would wait until it receive an input, but I don't think that's the case. The answer is more complicated and lies in threading which is used to run multiple threads (functions, tasks, etc) at the same time. This way it can measure the time at the same time it is asking for input. I don't know much about threading in Python but Stack Overflow does :)

Roar123 (446)

@Roar123 Let's go! It turns out my approach works, I just made a small mistake that I fixed now. I'd recommend using this instead of the Stack Overflow solution to avoid an extra import but check out threading too.

LoneAce (221)

@Roar123 Sorry but i think you misunderstood. I wanted to prevent input if the user takes too much time.

Roar123 (446)

@LoneAce There's no way to retract the input without using threading after a given amount of time but the function I wrote above returns 'Timed Out' if they took longer than the specified time. You can use that to tell the user that they took too much time. Preventing input is not necessarily the solution and is probably more complicated than you need.

LoneAce (221)

@Roar123 Thanks but I need to terminate not only input after a specified time. I tried threading but it just gives the illusion of a multitasking. I know that this is complicated, if it weren't I would not have asked it here. Thanks for your help anyway.

Roar123 (446)

@LoneAce Your answer should be in the select library.