Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect python warnings to a custom stream?

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?

like image 460
Paweł Hajdan Avatar asked May 13 '09 16:05

Paweł Hajdan


People also ask

How do you raise a warning in Python?

Python programmers issue warnings by calling the warn() function defined in this module. (C programmers use PyErr_WarnEx() ; see Exception Handling for details). Warning messages are normally written to sys.

How do I ignore deprecation warning in Python?

Use warnings. filterwarnings() to ignore deprecation warnings filterwarnings(action, category=DeprecationWarning) with action as "ignore" and category set to DeprecationWarning to ignore any deprecation warnings that may rise. Leave category unset to ignore all warnings.

What is DeprecationWarning in Python?

removing is danger because user may used that and if a developer want to remove a thing first have to notify others to don't use this feature or things and after this he can remove. and DeprecationWarning is this notification.


1 Answers

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.

like image 60
cobbal Avatar answered Sep 22 '22 03:09

cobbal