Skip to content
Sign upLog in
← Back to Community

How do I add limited input time to my code? (Python)

Profile icon
Seth01Master

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 you 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? Thank you so much!!

Answered by Coder100 [earned 5 cycles]
View Answer
Voters
Profile icon
DanielGGGGGGG
Profile icon
Seth01Master
Comments
hotnewtop
Profile icon
Coder100

then just call the function?

from threading import Timer def done(): pass # ... add your code here timeout = 5 t = Timer(timeout, print, ["Time's up!"]) t.start() entry = input('> ') t.cancel() done()
Profile icon
Seth01Master

@Coder100
The problem is, the timer is inside of the function it's calling. And other code that needs to be executed in its own type of order. I could give you access to the code I'm working on... that would probably make way more sense.

Profile icon
Coder100
Profile icon
Seth01Master

@Coder100
I invited you to edit

Profile icon
Coder100
Profile icon
OldWizard209
import time mint = input("How many seconds you want to time?:") timer = int(mint) while (timer != 0 ): timer=timer-1 time.sleep(1) print(timer)

You can modify this code and add if statements as you like.

Profile icon
Seth01Master

@abdullahrajput9
I would prefer the timer not to be visible until the the timer ends. also- i want the code to give you only a limited time to enter an input.

Profile icon
OldWizard209

You can remove the print statement and make an if statement like this.

if timer > 5: print("Time UP")
Profile icon
Seth01Master

@abdullahrajput9
ok, ill try it out. Thanks!