iamauser
iamauser

Reputation: 11489

Python direct exceptions in def to stdout

I have several defs designed like this :

def first():
    try:
       "Talking Business Here"
    except IOError, e:
       print e
    else:
       "Make a deal"

def second():
    try:
       "Business solution"
    except IOError, e:
       print e
       first()
    else:
        third()

def third():
    #Similar functionality


def main():
    second()

if __name__ == 'main':main()

I would like to collect all the except messages and print message into stdout. Then inside this python script, I would like to check the stdout and see if there is any message at all, something like :

if len(sys.stdout) > 0 :
    #Send me an email

Any help/suggestion is appreciated.

Upvotes: 1

Views: 804

Answers (2)

towi
towi

Reputation: 22307

You can just assign the file descriptors, I think:

import sys

oldStderr = sys.stderr
sys.stderr = sys.stdout

Now everything that goes to normally to stderr does now go to stdout.

With oldStderr you can "undo" the assignment when you don't want t anymore.

You can also collect everything in a String-Stream this way, if you create one before assigning it to stderr.

Upvotes: 2

abhishekgarg
abhishekgarg

Reputation: 1473

did you try this..

exeptions = []
def first():
    try:
       "Talking Business Here"
    except IOError, e:
       sys.stdout.write(e)
       exceptions.append(e)
    else:
       "Make a deal"

also you can try to append all the exceptions in a list and then

if len(exceptions) >0:
    "send me a mail"

Upvotes: 2

Related Questions