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?
+5
A:
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.
cobbal
2009-05-13 16:20:28
A:
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.
Kylotan
2009-05-13 16:57:28