Print only the message on warnings

PythonWarnings

Python Problem Overview


I'm issuing lots of warnings in a validator, and I'd like to suppress everything in stdout except the message that is supplied to warnings.warn().

I.e., now I see this:

./file.py:123: UserWarning: My looong warning message
some Python code

I'd like to see this:

My looong warning message

Edit 2: Overriding warnings.showwarning() turned out to work:

def _warning(
    message,
    category = UserWarning,
    filename = '',
    lineno = -1):
    print(message)
...
warnings.showwarning = _warning
warnings.warn('foo')

Python Solutions


Solution 1 - Python

There is always monkeypatching:

import warnings

def custom_formatwarning(msg, *args, **kwargs):
    # ignore everything except the message
    return str(msg) + '\n'

warnings.formatwarning = custom_formatwarning
warnings.warn("achtung")

Solution 2 - Python

Solution 3 - Python

Use the logging module instead of warnings.

Solution 4 - Python

Here's what I'm doing to omit just the source code line. This is by and large as suggested by the documentation, but it was a bit of a struggle to figure out what exactly to change. (In particular, I tried in various ways to keep the source line out of showwarnings but couldn't get it to work the way I wanted.)

# Force warnings.warn() to omit the source code line in the message
formatwarning_orig = warnings.formatwarning
warnings.formatwarning = lambda message, category, filename, lineno, line=None: \
    formatwarning_orig(message, category, filename, lineno, line='')

Just passing line=None would cause Python to use filename and lineno to figure out a value for line automagically, but passing an empty string instead fixes that.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionl0b0View Question on Stackoverflow
Solution 1 - PythonOtto AllmendingerView Answer on Stackoverflow
Solution 2 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 3 - PythonGeoff ReedyView Answer on Stackoverflow
Solution 4 - PythontripleeeView Answer on Stackoverflow