Archive

Archive for June, 2016

for / else and try / except / else

June 17, 2016 1 comment

Problem
What is that “else” in a for loop? And that “else” in an exception handler?

Solution
They can be confusing but in this thread I found a perfect way to remember what they mean. Asdayasman suggests that we should always annotate these “else” branches:

for _ in []:
    ...
else:  # nobreak
    ...

try:
    ...
except:
    ...
else:  # noexcept
    ...

To be honest, IMO it is best to avoid for / else completely.

Advertisements
Categories: python Tags: , , ,

email notification from a script

June 15, 2016 1 comment

Problem
You want to send an email to yourself from a script.

Solution
You can find here how to do it from a Bash script. That solution uses the mailx command.

Here is a simple Python wrapper for the mailx command:

#!/usr/bin/env python3
# coding: utf8

import os

DEBUG = True
# DEBUG = False

class NoSubjectError(Exception):
    pass

class NoRecipientError(Exception):
    pass

def send_email(to='', subject='', body=''):
    if not subject:
        raise NoSubjectError
    if not to:
        raise NoRecipientError
    #
    if not body:
        cmd = """mailx -s "{s}" < /dev/null "{to}" 2>/dev/null""".format(
            s=subject, to=to
        )
    else:
        cmd = """echo "{b}" | mailx -s "{s}" "{to}" 2>/dev/null""".format(
            b=body, s=subject, to=to
        )
    if DEBUG:
        print("#", cmd)
    #
    os.system(cmd)

def main():
    send_email(to="to@email.com",
               subject="subject")
    #
    send_email(to="to@email.com",
               subject="subject",
               body='this is the body of the email')

#############################################################################

if __name__ == "__main__":
    main()

You can also find this code as a gist.

Categories: python Tags: , ,