How to disable python warnings

2019-01-01 02:01发布

I am working with code with throws a lot of (for me at the moment) useless warnings using the warnings library. Reading (/scanning) the documentation I only found a way to disable warnings for single functions. But I don't want to change so much of the code.

Is there maybe a flag like python -no-warning foo.py?

What would you recommend?

7条回答
浅入江南
2楼-- · 2019-01-01 02:09

You can use this code at the top of the main.py:

def warn(*args, **kwargs):
    pass
import warnings
warnings.warn = warn
查看更多
流年柔荑漫光年
3楼-- · 2019-01-01 02:13

Did you look at the suppress warnings section of the python docs?

If you are using code that you know will raise a warning, such as a deprecated function, but do not want to see the warning, then it is possible to suppress the warning using the catch_warnings context manager:

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()

I don't condone it, but you could just surpress all warnings with this:

import warnings
warnings.filterwarnings("ignore")

Ex:

>>> import warnings
>>> def f():
...  print('before')
...  warnings.warn('you are warned!')
...  print('after')
>>> f()
before
__main__:3: UserWarning: you are warned!
after
>>> warnings.filterwarnings("ignore")
>>> f()
before
after
查看更多
忆尘夕之涩
4楼-- · 2019-01-01 02:14

This is an old question but there is some newer guidance in PEP 565 that to turn off all warnings if you're writing a python application you should use:

import sys
import warnings

if not sys.warnoptions:
    warnings.simplefilter("ignore")

The reason this is recommended is that it turns off all warnings by default but crucially allows them to be switched back on via python -W on the command line or PYTHONWARNINGS.

查看更多
孤独寂梦人
5楼-- · 2019-01-01 02:23

You can also define an environment variable (new feature in 2010 - i.e. python 2.7)

export PYTHONWARNINGS="ignore"

Test like this: Default

$ export PYTHONWARNINGS="default"
$ python
>>> import warnings
>>> warnings.warn('my warning')
__main__:1: UserWarning: my warning
>>>

Ignore warnings

$ export PYTHONWARNINGS="ignore"
$ python
>>> import warnings
>>> warnings.warn('my warning')
>>> 
查看更多
妖精总统
6楼-- · 2019-01-01 02:26

if don't want to complicate then import warnings warnings.filterwarnings("ignore", category=FutureWarning)

查看更多
何处买醉
7楼-- · 2019-01-01 02:29

There's the -W option.

python -W ignore foo.py

查看更多
登录 后发表回答