Last active
January 22, 2016 14:34
-
-
Save albop/8c94e8694369474f7c85 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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