End Python Code After 60 Seconds
Below there is some fully functioning code. I am planning to execute this code through command line, however I would like it to end after 60 seconds. Does anyone know the best way
Solution 1:
Try this out:
import os
import time
from datetime import datetime
from threading import Timer
defexitfunc():
print"Exit Time", datetime.now()
os._exit(0)
Timer(5, exitfunc).start() # exit in 5 secondswhileTrue: # infinite loop, replace it with your code that you want to interruptprint"Current Time", datetime.now()
time.sleep(1)
There are some more examples in this StackOverflow question: Executing periodic actions in Python
I think the use of os._exit(0)
is discouraged, but I'm not sure. Something about this doesn't feel kosher. It works, though.
Solution 2:
You could move your code into a daemon thread and exit the main thread after 60 seconds:
#!/usr/bin/env pythonimport time
import threading
deflisten():
print("put your code here")
t = threading.Thread(target=listen)
t.daemon = True
t.start()
time.sleep(60)
# main thread exits here. Daemon threads do not survive.
Solution 3:
Use signal.ALARM
to get notified after a specified time.
import signal, os
defhandler(signum, frame):
print'60 seconds passed, exiting'
cleanup_and_exit_your_code()
# Set the signal handler and a 60-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(60)
run_your_code()
From your example it is not obvious what the code will exactly do, how it will run and what kind of loop it will iterate. But you can easily implement the ALARM
signal to get notified after the timeout has expired.
Solution 4:
This is my favorite way of doing timeout.
deftimeout(func, args=None, kwargs=None, TIMEOUT=10, default=None, err=.05):
if args isNone:
args = []
elifhasattr(args, "__iter__") andnotisinstance(args, basestring):
args = args
else:
args = [args]
kwargs = {} if kwargs isNoneelse kwargs
import threading
classInterruptableThread(threading.Thread):
def__init__(self):
threading.Thread.__init__(self)
self.result = Nonedefrun(self):
try:
self.result = func(*args, **kwargs)
except:
self.result = default
it = InterruptableThread()
it.start()
it.join(TIMEOUT* (1 + err))
if it.isAlive():
return default
else:
return it.result
Solution 5:
I hope this is an easy way to execute a function periodically and end after 60 seconds:
import time
import os
i = 0defexecuteSomething():
global i
print(i)
i += 1
time.sleep(1)
if i == 10:
print('End')
os._exit(0)
whileTrue:
executeSomething()
Post a Comment for "End Python Code After 60 Seconds"