So I'm using method_x from a third party library which prints a warning every time I use it. Since I'm coding something that is meant to get user input from the cli I want to block this annoying prints.
import module_x
module_x.method_x() # Has expected behaviour but prints an annoying warning
Is there something I can do to block all the print statements inside a function? Maybe wrapping the method with something or disable stdout temporarily?
Edit: I ended up using a method of the logging module that captures the warnings and redirects them to a log file. Here's the decorator I made:
logging.basicConfig(filename='log/log', level=logging.WARNING)
class redirect_warnings_to_log(object):
def __init__(self, f):
self.f = f
def __call__(self, args):
logging.captureWarnings(True)
self.f(args)
logging.captureWarnings(False)
And here's the decorated method that was printing the warnings:
@redirect_warnings_to_log
def tweet(message):
twt = api.PostUpdate(message)
As the question says -
I'm using method_x from a third party library which prints a warning every time I use it.
If method_x
is using Python's warnings
module. Then you can use warnings.catch_warnings()
along with with
statement and warnings.simplefilter()
to ignore the warnings , so that warnings are suppressed.
Example -
>>> import warnings
>>> def f():
... warnings.warn("Some warning!")
...
>>> f()
__main__:2: UserWarning: Some warning!
>>> with warnings.catch_warnings():
... warnings.simplefilter("ignore")
... f()
...
Please note this only temporarily suppress warnings, only within the with
block, in the f() is used outside the if
block, then it does not suppress those warnings.
From documentation -
While within the context manager all warnings will simply be ignored. This allows you to use known-deprecated code without having to see the warning while not suppressing the warning for other code that might not be aware of its use of deprecated code. Note: this can only be guaranteed in a single-threaded application. If two or more threads use the catch_warnings context manager at the same time, the behavior is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With