如何确定模块名称以过滤特定的Python警告?

时间:2018-09-20 12:43:59

标签: python command-line warnings

使用Python,可以使用以下命令行语法filter specific warnings

-W action:message:category:module:line

但是对于特定警告,如何确定module的正确值?

考虑以下示例:

使用(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__

如果只想忽略该特定的导入警告,那么如何找到要使用的模块名称?以下命令似乎都不正确。他们仍然发出警告。

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"

1 个答案:

答案 0 :(得分:3)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li class="dropdown"> <a class="dropdown-toggle" href="#" id="builders">Builders<i class="fa fa-caret-down" aria-hidden="true"></i></a> <ul class="dropdown-menu"> <li><a href="gurgaon.php">Gurgaon</a></li> <li><a href="<?php echo base_url();?>all-india" class="active">All India</a></li> <li><a href="gurgaon-projects.php">Gurgaon Projects</a></li> <li><a href="<?php echo base_url();?>home/property_list">Property List</a></li> </ul> </li> </ul>警告实际上来自import.c,但是您需要使用ImportWarning进行过滤,警告消息中的堆栈不完整,内部堆栈被省略。您可以通过覆盖_frozen_importlib获取此信息:

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

btw python -Werror::ImportWarning:_frozen_importlib -c 'import lxml.etree' ignored by default