代码之家  ›  专栏  ›  技术社区  ›  Ian Mackinnon

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

  •  7
  • Ian Mackinnon  · 技术社区  · 6 年前

    用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 回复  |  直到 6 年前
        1
  •  3
  •   georgexsh    5 年前

    这个 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'
    

    顺便说一句 进口警告 ignored by default .