Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print only the message on warnings

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') 
like image 423
l0b0 Avatar asked Feb 02 '10 20:02

l0b0


People also ask

How do I stop print warnings in Python?

warnings are output via stderr and the simple solution is to append '2> /dev/null' to the CLI. this makes a lot of sense to many users such as those with centos 6 that are stuck with python 2.6 dependencies (like yum) and various modules are being pushed to the edge of extinction in their coverage.

What is DeprecationWarning?

DeprecationWarning errors are logged by the Node. js runtime when your code (or one of the dependencies in your code) calls a deprecated API. These warnings usually include a DEP deprecation code. They are logged using console.

What is warnings library in Python?

Source code: Lib/warnings.py. Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn't warrant raising an exception and terminating the program.


2 Answers

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") 
like image 169
Otto Allmendinger Avatar answered Sep 28 '22 18:09

Otto Allmendinger


Monkeypatch warnings.showwarning() with your own custom function.

like image 41
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 17:09

Ignacio Vazquez-Abrams