import sys, subprocess, click

def writeflush(dest, s):
    dest.write(s)
    dest.flush()

def get_headers(line):
    """
    Parse Supervisor message headers.
    """

    return dict([x.split(':') for x in line.split()])

def supervisor_events(stdin, stdout):
    """
    An event stream from Supervisor.
    """

    while True:

        writeflush(stdout, 'READY\n')

        line = stdin.readline()
        headers = get_headers(line)
        payload = stdin.read(int(headers['len']))
        payload = payload.split('\n')
        yield payload[0], '\n'.join(payload[1:])
        writeflush(stdout, 'RESULT 2\nOK')

email_prefix = """Heads-up! Data coming... \n\n"""

@click.command()
@click.option('--process', '-p', default='', help='Name of process to select. Default is all.')
@click.option('--select', '-s', default='', help='Select lines containing this string. Default is all.')
@click.option('--destination', '-d', default='log', help='Send lines to either \'stderr\' or \'email\'. Default is log (which is routed via stderr)')
def main(process, select, destination):
    for ehead, edata in supervisor_events(sys.stdin, sys.stdout):
        ehead_parsed = get_headers(ehead)

        if process in ehead_parsed['processname']:    # select process from head
            if select in edata:     # select by string in edata
                if not len(edata):                # state event has no data. ehead becomes edata
                    edata = ehead   
                    
                # send data along
                if destination == 'log':
                    writeflush(sys.stderr, edata + '\n')
                elif destination == 'email':
                    subprocess.call("""echo "%s" | mailx -s 'Supervisor Event (process %s and select %s)' caseyjlaw@gmail.com""" % (email_prefix+str(edata), process, select), shell=True)

if __name__ == '__main__':
    main()

@@ -637,33 +637,148 @@
  %22%22%22
-Heads-up! Data coming... 
+Message for you from realfast... %5Cn%5Cn ====================================%5Cn%5Cn%22%22%22%0Aemail_suffix = %22%22%22%5Cn%5Cn====================================
 %5Cn%5Cn
@@ -1150,16 +1150,156 @@
 derr)')%0A
+@click.option('--addresses', '-a', default='caseyjlaw@gmail.com', help='If destination=email, where to send event? (comma-separated list)')%0A
 def main
@@ -2022,35 +2022,18 @@
 ct %25s)' 
-caseyjlaw@gmail.com
+%25s
 %22%22%22 %25 (e
@@ -2054,16 +2054,29 @@
 r(edata)
++email_suffix
 , proces
@@ -2084,16 +2084,27 @@
 , select
+, addresses
 ), shell

clean up of email option