I have the following code and I want to stop the program if the condition is not true for a certain period of time. Suppose the condition (sum>99999) is false for a period of 10 seconds, then this program stops and gives present sum values. I am on Windows. Any idea how to do it in Windows.
for j in i:
sum=sum+A[j]
if(sum>99999):
print("Current sum is",sum)
This should accomplish what you're describing.
import time
import sys
start_time = time.time()
for j in i:
sum = sum + A[j]
if sum > 99999:
print("Current sum is ", sum)
start_time = time.time() # reset timer if the condition becomes true
elif time.time() - start_time >= 10:
print("Current sum is ", sum)
sys.exit()
Try this:
import time
import sys
start = time.time()
for j in i:
sum += A[j]
if sum > 99999:
print(sum)
elif time.time() - start > 10:
print(sum)
break # if you just want to exit the loop or sys.exit() if you want to exit the program
Sometimes an iteration is heavy enough to render technique proposed by other answers pretty useless. If you don't have access to break execution upon condition, this or that recipes would be helpful.
I will copy the simpler one (and the one I prefer in my code):
import threading
def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = None
def run(self):
try:
self.result = func(*args, **kwargs)
except:
self.result = default
it = InterruptableThread()
it.start()
it.join(timeout_duration)
if it.isAlive():
return default
else:
return it.result
import sys
import time
start_time = time.time()
time_limit = 2
if (comdition):
if((time.time() - start_time) > time_limit):
sys.exit()
else:
#more stuff here
Related
I have this code to stop a function at a specific time. I would loop through the function and then break the function, if it takes too long, is there a better way to do it?
import time
def function_one()
rec = (time.time())
print("im starting")
ans = str(time.time() - rec)
ans = (round(float(ans), 15))
print("this is where im doing something code")
while ans < 10:
return function_one()
break
You can make it simpler like this:
import time
def function_one():
start_time = time.time()
while True:
print('Function doing something ...')
if time.time() - start_time > 10:
break
function_one()
Here, I'm using a while loop just to keep the function running, but that depends on the details of your function.
In general, what you need is:
set the start time
do whatever the function is supposed to be doing;
check if it's been running for too long and, in case it has, you can simply return.
So, something like:
import time
def function_one():
start_time = time.time()
# do your job
if time.time() - start_time > 10:
return something
function_one()
If you want to stop a function after a set amount of time has passed I would use a while loop and do something like this.
import time
def function_one():
start = (time.time()) #start time
limit = 1 #time limit
print("im starting")
while (time.time() - start) < limit:
#input code to do here
pass
print(f"finished after {time.time() - start} seconds")
function_one()
My code:
def timer():
while True:
try:
when_to_stop = 90
except KeyboardInterrupt:
break
except:
print("error, please star game again")
while when_to_stop > 0:
m, s = divmod(when_to_stop, 60)
h, m = divmod(m, 60)
time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" +
str(s).zfill(2) # got cut off, belongs to the line before this
print("time:", time_left + "\r", end="")
if time_left == 0:
print("TIME IS UP!")
time.sleep(1)
when_to_stop -= 1
This works perfectly fine, except that time.sleep means my whole program sleeps, so anything after that while stop for 90 seconds. Any way to fix that?(or make a new timer without time.sleep?)
I think that, alternatively, you could keep track of when the timer starts, and check the time by seeing if the time that's passed is longer than the timer is supposed to last. I'm not sure how much you know about classes and objects in Python, but here is the solution that came to mind:
import datetime
class Timer:
def __init__(self,**kwargs):
self.start = datetime.datetime.now()
self.length = datetime.timedelta(**kwargs)
self.end = self.start+self.length
def isDone(self):
return (self.end-datetime.datetime.now()).total_seconds()<=0
def timeLeft(self):
return self.end-datetime.datetime.now()
def timeElapsed(self):
return datetime.datetime.now()-self.start
Even if you don't quite understand the class itself, if you put it in your code it should work like a charm:
#This has the same options as:
#class datetime.timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks)
t = Timer(days=2)
while(not t.isDone()):
#Do other game stuff here....
time_left = t.timeLeft()
print(f"time: {time_left}")
#And here....
print("Done now")
import time
import os
T = int(input("Enter desired time for the timer - "))
t = time.localtime(time.time())
def Timer():
while ((t.tm_sec) != T+(t.tm_sec)):
return t
else:
os.system("start C:/Users/Public/Music/Sample Music")
Timer()
I have been working on this timer and can't get it to work. Basically, I want it to play the song I have in my system when the time is up. I have been trying to write this program and I can't understand why my code doesn't run the way I want it to. Could someone please point out if there's a mistake in it?
What's wrong with your code specifically is this condition
(t.tm_sec) != T+(t.tm_sec)
The problem is that t's value was set when you did (t.tm_sec) != T+(t.tm_sec). Once that is set, the same value of t will be used. I think you assumed that t will be recomputed every time in the while statement. To recompute t every time you can do:
import time
import os
T = int(input("Enter desired time for the timer - "))
snap_time = time.localtime(time.time())
def Timer():
t = time.localtime(time.time())
while t.tm_sec < (T + snap_time.tm_sec):
t = time.localtime(time.time())
os.system("start C:/Users/Public/Music/Sample Music")
Timer()
t.tm_sec is fixed, so unless T is 0 the condition will never be False, so the else block will never be executed. On top of that there is return in the loop, which mean it will run only one iteration and exit the function. Try
T = int(input("Enter desired time for the timer - ")) + time.time()
def Timer():
while time.time() < T:
pass
else:
os.system("start C:/Users/Public/Music/Sample Music")
You can also remove the else
def Timer():
while time.time() < T:
pass
os.system("start C:/Users/Public/Music/Sample Music")
I don't think your example makes proper use of while (and return). How about a much simpler version:
import time
import os
T = int(input("Enter desired time for the timer - "))
def Timer():
time.sleep(T)
os.system("start C:/Users/Public/Music/Sample Music")
Timer()
i made simple timer
this timer has two function
1.countdown 2. stopwatch
btw i want to use timer in game
ex) countdown stop > game finish
So i want return value in timer..
but i can't
plz help me :)
import time
import threading
count = 0
def start_timer(count):
print(count)
count -= 1
timer = threading.Timer(1, start_timer, args=[count])
timer.start()
if count == 0:
print("game start!")
timer.cancel()
def stop_watch():
now = time.time()
check = input("press button\n")
stop = time.time()
print("time : %0.3f" % (stop - now))
i can't get return value
I want to write a function called boom(h,m,s) that after input from main starts printing in HH:MM:SS format the countdown clock, and then prints "boom".
I'm not allowed to use existing modules except the time.sleep(), so I have to base on While\For loops.
import time
def boom(h,m,s):
while h>0:
while m>0:
while s>0:
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s-=1
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s=59
m-=1
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s=59
m=59
h-=1
while h==0:
while m==0:
while s>0:
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s-=1
print ("BooM!!")
I figured how to calculate the seconds part, but when I input zeros on H and M parameters, it's messing with the clock.
The problem is here:
while h==0:
while m==0:
while s>0:
If m == 0, and s == 0 the while loop doesn't break, so there is an infinite loop.
Just add an else clause to the (last and) inner-most while, like so:
while s>0:
...
else: # executed once the above condition is False.
print ('BooM!!')
return # no need to break out of all the whiles!!
just convert it all to seconds and convert it back when you print ...
def hmsToSecs(h,m,s):
return h*3600 + m*60 + s
def secsToHms(secs):
hours = secs//3600
secs -= hours*3600
mins = secs//60
secs -= mins*60
return hours,mins,secs
def countdown(h,m,s):
seconds = hmsToSecs(h,m,s)
while seconds > 0:
print "%02d:%02d:%02d"%secsToHms(seconds)
seconds -= 1
sleep(1)
print "Done!"