all Python 3warningsfunction
warnings.formatwarning()
displaying warnings
Returns a warning formatted the standard way, "file:line: Category: message" — the text that showwarning() prints.
Syntax
text = warnings.formatwarning(message, category, filename, lineno, line=None)
Replacing warnings.formatwarning changes how every displayed warning looks without touching the filters: this is how you drop the second line with source code or add a timestamp. The string ends in '\n'; if the named file is readable, the second line is the source text from it (via linecache), otherwise there is none. Warnings routed to logging by captureWarnings() are formatted by this function too.
Examples
import warnings
print(repr(warnings.formatwarning('мало памяти', ResourceWarning, 'job.py', 7)))
# → 'job.py:7: ResourceWarning: мало памяти\n'
import sys, warnings
def short(message, category, filename, lineno, line=None):
return f'{category.__name__}: {message}\n'
warnings.formatwarning = short
warnings.showwarning('диск почти полон', UserWarning, 'job.py', 3, file=sys.stdout)
# → UserWarning: диск почти полон
See also
Open in the full glossarydocs.python.orgReport an inaccuracy