【问题标题】:How to determine the module name to filter a specific Python warning?如何确定模块名称以过滤特定的 Python 警告?
【发布时间】:2019-02-24 18:50:28
【问题描述】:

使用 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"

【问题讨论】:

  • 您使用的是哪个 Python 版本?对我来说(Win7,Py3.4)没有警告。
  • 嗯,可能是因为我有lxml
  • 它在问题的 pipenv 命令中。如果你有 pipenv,你也可以使用 lxml 的确切版本来运行它。虽然我真的对确定模块名称的通用方法感兴趣,而不仅仅是针对这种情况。谢谢。
  • 当我阅读 Python 3.7.0 Documentation 时,-Wignore 之间应该有 NO 空格。您的案例示例describing-warning-filters
  • @stovfl,我相信标志和值之间的空格是可选的。您可以验证以下是否有效(尽管它会忽略 all 导入警告):python -W error -W ignore::ImportWarning -c "from lxml import etree"

标签: python command-line warnings


【解决方案1】:

ImportWarning的警告,其实是来自import.c,但需要用_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

您可以通过以下方式验证这一点:

python -Werror::ImportWarning:_frozen_importlib -c 'import lxml.etree'

顺便说一句,ImportWarningignored by default

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-04
    • 2013-06-16
    • 2020-10-31
    • 1970-01-01
    • 2018-08-12
    • 2015-09-02
    • 1970-01-01
    相关资源
    最近更新 更多