+ 5
How do I make a program stop after a certain time?
I need to make a program stop after 30 seconds have passed the user has to add some inputs during that time
13 Respuestas
+ 1
In console mode, the only way I could do it is determine after the fact if the allocated time has passed.
You would choose one way of getting the time from 'time' module, take the time in a variable and start the inputs.
After all inputs are given, you check the time again and compare the two times to check if the time span has passed.
That's not like a stop clock: The user would be able to drag on their input for an hour; but after he/she finally gave them, you can hand out 'failure'.
Is that good enough for your purpose?
+ 27
You just need to use the function sleep() of the module time:
import time
time.sleep(30*60)
+ 4
Note, input is normally *blocking* in Python. It sounds like you want to check for input without hanging (which would prevent you from checking the clock).
Here's an article about non-blocking stdin:
https://repolinux.wordpress.com/2012/10/09/non-blocking-read-from-stdin-in-python/
+ 2
HonFu I'll try that sounds good enough thank you so much!!
+ 2
HonFu I just tried that and yeah it's more simple I used two variables just as you said to calculate the time before and after and it works so yeah thanks you again
+ 2
Use the "return" syntax.
Or perhaps the clearInterval()
I'm pretty sure it'll work😃
+ 1
HonFu is like a game where you have to guess a number but I want to put a timer like 20 or 30 seconds and I need the program to stop after that time but the user has to be able to guess the number so .sleep() wont work
+ 1
I just tried around myself; time.time seems to be simplest. You get the computer time in seconds and can just subtract the first take from the second.
+ 1
Good to hear! :)
+ 1
Kirk Schafer That was totally new for me thanks for the article I'll try to check more info about about that nonblocking input
0
Gustavo, do you want to stop execution of the program for a certain time where the user has time to read the screen? (Then sleep I suppose.)
Or do you want to set some sort of timer while the program is still running? (Like entering answers to question within a given time limit?)
0
import multiprocessing
import time
# Your foo function
def foo(n):
for i in range(10000 * n):
print("Tick")
time.sleep(1)
if __name__ == '__main__':
# Start foo as a process
p = multiprocessing.Process(target=foo, name="Foo", args=(10,))
p.start()
# Wait 10 seconds for foo
time.sleep(10)
# Wait a maximum of 10 seconds for foo
# Usage: join([timeout in seconds])
p.join(10)
# If thread is active
if p.is_alive():
print("Foo is running... let's kill it...")
# Terminate foo
p.terminate()
p.join()
- 1
set a timer