This is a bit of a follow-up to the question: Disable warnings originating from scipy. The answer succeeds in redirecting any output intended for stdout
to /dev/null
. The new goal is to capture stdout
as it's being printed so that I can examine it for the presence of certain strings. Here's a partial solution that raises a MyError
whenever a string containing "warning" is printed to stdout
using something like print
or sys.stdout.write()
:
import sys
import contextlib
class Warning_Catcher():
def write(self, string):
if 'warning' in string:
raise MyError
@contextlib.contextmanager
def capture_warning():
oldout, sys.stdout = sys.stdout, Warning_Catcher()
try:
yield sys.stdout
except MyError:
# handle error
finally:
sys.stdout = oldout
with capture_warning() as out:
print 'warning'
However, it does not redirect things at the file descriptor level as explained in this other post on redirection here.
My question is then: can I capture all output to stdout
in a manner similar to the above code, raising an error if a certain string is found? The key is that I don't want to be writing to an actual file (which is why the original plan was to write everything to /dev/null
). It seemed like using the 'tempfile' module with a moderate buffer size might work as this would allow me to use dup2()
to completely redirect things, but this approach hasn't been met with success.