Redirecting STDOUT to a Python Variable

Hans Mulder hansmu at xs4all.nl
Sun Sep 23 03:38:13 EDT 2012


On 22/09/12 23:57:52, ross.marsden at gmail.com wrote:
> To capture the traceback, so to put it in a log, I use this
> 
> import traceback
> 
> def get_traceback(): # obtain and return the traceback
>     exc_type, exc_value, exc_traceback = sys.exc_info()
>     return ''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)) 

This could be coded more succinctly as

import sys, traceback

def get_traceback(): # obtain and return the traceback
    return ''.join(traceback.format_exception(*sys.exc_info()))

> Suppose I have a script run by the scheduler, this captures the traceback form any problems and emails them.
> 
> if __name__ == '__main__':
>     try: 
>         Runs_unattended()
>     except:
>         send_mail(send_from = yourEmailAddress,
>               send_to = [ yourEmailAddress ], subject = 'Runs_unattended',
>               text = '%s' % get_traceback(),
>               files = [], server=yourLocalSMTP)

Errhm, '%s' % get_traceback() is equiavalent to get_traceback()
How about:

if __name__ == '__main__':
    try:
        Runs_unattended()
    except:
        send_mail(send_from = yourEmailAddress,
              send_to = [ yourEmailAddress ],
              subject = 'Runs_unattended',
              text = get_traceback(),
              files = [],
              server=yourLocalSMTP)



Hope this helps,

-- HansM



More information about the Python-list mailing list