How to redirect stderr to variable in Python 2.7?
Question: 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](https://wrongsideofmemphis.wordpress.com/2010/03/01/store-standard-
output-on-a-variable-in-python/) 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


Answer: 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

