0

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

2
  • Use sys.stderr instead of sys.stdout and do what the post says. But why do you need it. Who is writing to stderr? Commented Aug 4, 2015 at 18:04
  • What part of the linked post don't you understand? Commented Aug 4, 2015 at 18:31

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

In my case the interpreter protests pointing at the last line, with a message: "AttributeError: 'file' object attribute 'write' is read-only"
0
  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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.