Reputation: 409
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
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
Reputation: 3360
Upvotes: 0