Skip to content

Instantly share code, notes, and snippets.

@albop
Last active Jan 22, 2016
Embed
What would you like to do?
"""
Filename: watcher.py
Authors: Pablo Winant
Time long computation and send a message when finished.
"""
import contextlib
@contextlib.contextmanager
def watcher(task_name=None, email=None):
import time
import datetime
t = time.time()
starting_date = datetime.datetime.now()
try:
yield
finally:
finishing_date = datetime.datetime.now()
delta = finishing_date - starting_date
if delta.days == 0:
print(delta)
dd = delta.seconds + delta.microseconds/1e6
elapsed = "{} seconds".format(dd)
else:
elapsed = "{} days and {} seconds".format(delta.days, delta.seconds)
short_msg = "Task {} finished after {} seconds.".format(task_name, elapsed)
long_msg = '''
Task {} completed.
Started: {}
Finished: {}
Elapsed: {}'''.format(task_name, starting_date.isoformat(), finishing_date.isoformat(), str(delta))
print(short_msg)
if email:
try:
import smtplib
from email.mime.text import MIMEText
msg = MIMEText(long_msg)
msg['Subject'] = short_msg
msg['From'] = email
msg['To'] = email
s = smtplib.SMTP('localhost')
s.sendmail(email, msg.as_string())
s.quit()
except Exception as e:
import warnings
warnings.warn("Impossible to send email using 'smtplib'")
def test_watcher():
from time import sleep
def fun(n):
sleep(n)
with watcher("Sleep"):
sleep(1)
with watcher(task_name="Sleep", email='pablo.winant@gmail.com'):
sleep(1)
if __name__ == '__main__':
test_watcher()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment