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?
            Asked
            
        
        
            Active
            
        
            Viewed 6,938 times
        
    3 Answers
20
            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.
 
    
    
        Paweł Hajdan
        
- 18,074
- 9
- 49
- 65
 
    
    
        cobbal
        
- 69,903
- 20
- 143
- 156
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.
 
    
    
        Kylotan
        
- 18,290
- 7
- 46
- 74
0
            
            
        import sys
import StringIO
sys.stdout = StringIO.StringIO()
 
    
    
        mtasic85
        
- 3,905
- 2
- 19
- 28
- 
                    2Just 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. – eacousineau Feb 03 '12 at 15:44