Dani Valverde
Dani Valverde

Reputation: 409

How to redirect stderr to variable in Python 2.7?

I am trying to redirect the stderr of a script to a variable to use it in if/else statements. What I need is the program to behave in one way or another according to the stderr. I have found this post using StringIO which may suit my needs, but I cannot figure out how to make it to redirect stderr. I'm sure it is quite easy, but I'm quite new to python and any detailed help will be really appreciated. Thanks!

Dani

Upvotes: 0

Views: 1982

Answers (2)

Piotr Dabkowski
Piotr Dabkowski

Reputation: 5939

In order to intercept writes to stderr use following 'hack':

import sys
STDERR = ''

def new_stderr(old):
    def new(*args):
        # put your code here, you will intercept writes to stderr
        print('Intercepted: ' + repr(args))
        global STDERR   # add new write to STDERR 
        STDERR += args[0]  
        old(*args)
    return new

sys.stderr.write = new_stderr(sys.stderr.write)

All writes to stderr will be stored in STDERR variable

Upvotes: 2

Robert Jacobs
Robert Jacobs

Reputation: 3360

  1. Make a copy of sys.stderr.
  2. Open some StringIO variable (may already be done)
  3. Assign variable to sys.stderr
  4. All writes to stderr will now go to the new file.
  5. Copy your saved original version of sys.stderr back to return to old behavior

Upvotes: 0

Related Questions