12

Let's say I have a file-like object like StreamIO and want the python's warning module write all warning messages to it. How do I do that?

3 Answers 3

23

Try reassigning warnings.showwarning i.e.

#!/sw/bin/python2.5

import warnings, sys

def customwarn(message, category, filename, lineno, file=None, line=None):
    sys.stdout.write(warnings.formatwarning(message, category, filename, lineno))

warnings.showwarning = customwarn
warnings.warn("test warning")

will redirect all warnings to stdout.

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

Comments

0

I think something like this would work, although it's untested code and the interface looks like there is a cleaner way which eludes me at present:

import warnings

# defaults to the 'myStringIO' file
def my_warning_wrapper(message, category, filename, lineno, file=myStringIO, line=None):
    warnings.show_warning(message, category, filename, lineno, file, line)    

warnings._show_warning = my_warning_wrapper

A look inside Lib\warnings.py should help put you on the right track if that isn't enough.

Comments

0
import sys
import StringIO

sys.stdout = StringIO.StringIO()

1 Comment

Just a note - this is a different implementation from io.StringIO StringIO.StringIO does not have methods such as fileno() defined, while io.StringIO has fileno() defined but not implemented.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.