With Python one can filter specific warnings using the following command line syntax:
-W action:message:category:module:line
But how can one determine the correct value for module
for a particular warning?
Consider the following example:
Using (pipenv --python 3.6.5 install lxml==4.2.4
)
> python -W error -c "from lxml import etree"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "src/lxml/etree.pyx", line 75, in init lxml.etree
File "src/lxml/_elementpath.py", line 56, in init lxml._elementpath
ImportWarning: can't resolve package from __spec__ or __package__, falling back on __name__ and __path__
If one wanted to ignore only that specific import warning, how does one find the module name to use? None of the following commands appear to be correct. They all still emit the warning.
python -W error -W ignore::ImportWarning:lxml -c "from lxml import etree"
python -W error -W ignore::ImportWarning:lxml.etree -c "from lxml import etree"
python -W error -W ignore::ImportWarning:lxml._elementpath -c "from lxml import etree"
python -W error -W ignore::ImportWarning:etree -c "from lxml import etree"
python -W error -W ignore::ImportWarning:_elementpath -c "from lxml import etree"
python -W error -W 'ignore::ImportWarning:lxml[.*]' -c "from lxml import etree"
If we don't want to fix the warning, then we can suppress it with the @SuppressWarnings annotation. This annotation allows us to say which kinds of warnings to ignore.
If you wish to squelch deprecation warnings, you can start Python with -Wi::Deprecation. This sets all deprecation warnings to ignored. There is also an Astropy-specific AstropyDeprecationWarning which can be used to disable deprecation warnings from Astropy only.
import warnings warnings. filterwarnings('ignore') print('The script still runs. ') To suppress any warnings in the script, import the warnings library, and pass the filterwarnings() function the argument ignore .
the ImportWarning
warnings, in fact, is from import.c, but you need to filter with _frozen_importlib
, the stacks in the warning message are incomplete and internal stacks are omitted. you could obtain this info by overridden warnings.showwarning
:
import warnings
def showwarning(message, category, filename, lineno, file, line):
print(filename)
warnings.showwarning = showwarning
warnings.resetwarnings() # allow all warnings
from lxml import etree
you could verify this by:
python -Werror::ImportWarning:_frozen_importlib -c 'import lxml.etree'
btw ImportWarning
is ignored by default.
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