How to redirect python stderr to string on display

I am compiling stderr from my script to later save to the database with:

ostderr = sys.stderr
sys.stderr = StringIO()

# do stuff

mymodel.errors = sys.stderr.getvalue()
mymodel.save()
print mymodel.errors
sys.stderr = ostderr

Unfortunately, this makes it difficult to accidentally debug, because if any errors occur, I will not see them until the script completes.

How do I remove stderr in a string, as I do above, but still display it in real time on the console?

+3
source share
1 answer

Use a file-like object that saves and prints to a regular stderr. Sort of:

class TeeFiles(object):
    def __init__(self, file):
        self.sio = StringIO()
        self.file = file

    def write(self, txt):
        self.sio.write(txt)
        self.file.write(txt)

sys.stderr = TeeFiles(sys.stderr)

# do stuff

mymodel.errors = sys.stderr.sio.getvalue()
mymodel.save()
sys.stderr = sys.stderr.file

You may need to support things like closed, flushetc., depending on what is going on #do stuff. It might be easier if you inherited from StringIO.

+3
source

All Articles