【问题标题】:Python: Disable iptcinfo warningPython:禁用 iptcinfo 警告
【发布时间】:2018-05-18 09:10:06
【问题描述】:

我正在使用 iptcinfo Python 模块从图片中获取元数据,但它向我抛出了很多此类(无用)警告:

('警告:字符集识别问题', "'\x1b'")

这是什么意思,我该如何删除这些警告(或防止它们发生),因为它们对我的代码似乎并不重要?

我的代码很简单:

import iptcinfo
iptc = iptcinfo.IPTCInfo("DSC05647.jpg") 

【问题讨论】:

  • 请出示代码sn-p。
  • @mouche 我刚刚添加了一个代码 sn-p。在“导入”之后插入代码不会改变任何内容
  • 您使用的是哪个版本的 iptcinfo?不知道的可以试试打印iptcinfo.__version__看看。
  • 这就是我的回答所指的版本。请参阅我对调试记录器和级别的编辑。
  • 我还没有尝试过,但我认为问题可能是图像中的图像元数据相关信息是 unicode,这就是库出现问题的原因。我希望您尝试 Python 3 的原因是,如果问题在同一版本中得到解决,它会给出一个想法。 Python 3 默认使用 unicode,所以如果我们知道它在 Python 3 中工作,我们确信这是 Python 2 的 unicode/str 转换问题。所以如果你可以在 Python 3 中尝试,这将有助于更快地找到一些解释

标签: python warnings iptc


【解决方案1】:

问题是您使用的模块做了一些您不希望模块做的事情。

print (
       'WARNING: problems with charset recognition',
      repr(temp))

嗯,不能像那样禁用的东西。但是它们是关于如何实现相同目标的良好 SO 线程。

Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call

Suppress calls to print (python)

因此将两者结合起来

import iptcinfo

origianl_IPTCInfo = iptcinfo.IPTCInfo

def patch_IPTCInfo(*args, **kwargs):
    import os, sys

    class HiddenPrints:
        def __enter__(self):
            self._original_stdout = sys.stdout
            sys.stdout = open('/dev/null', 'w')

        def __exit__(self, exc_type, exc_val, exc_tb):
            sys.stdout = self._original_stdout

    with HiddenPrints():
        return origianl_IPTCInfo(*args, **kwargs)

iptcinfo.IPTCInfo = patch_IPTCInfo

iptc = iptcinfo.IPTCInfo("/Users/tarunlalwani/Downloads/image.jpg")
print(iptc)

而且效果很好

【讨论】:

  • 还有一点需要注意,github上的代码和通过pip安装的代码有些不同。可能是最近没有推送包或使用最新代码
【解决方案2】:

This line in the code 似乎正在生成警告:

LOG.warn('problems with charset recognition %s', repr(temp))

您看到此消息是因为 Python 日志记录模块的默认日志记录级别是“警告”。

在您的代码中,您可以将库的记录器的 logging level 修改为更高,这样您就不会看到警告:

import logging
iptcinfo_logger = logging.getLogger('iptcinfo')
iptcinfo_logger.setLevel(logging.ERROR)

编辑:对于故障排除,这里有一个 sn-p 来查看每个记录器的级别:

for logger_name in logging.Logger.manager.loggerDict:
    logger_level = logging.getLogger(logger_name).level
    print logger_name, logging.getLevelName(logger_level)

【讨论】:

  • 我刚刚尝试了该代码,但仍然收到警告
  • 你是在导入iptcinfo之后运行函数之前做的吗?
  • 查看 Python 的 logging module 以更好地调试哪些记录器处于活动状态以及它们所处的记录级别。
  • 我尝试了代码来查看级别。 iptcinfo 确实设置为 ERROR 但我仍然收到警告消息!
  • @Sulli 抱歉,我不确定你发生了什么事。
【解决方案3】:

首先,我认为 iptcinfo 应该与 Python 2 完美配合。

另一种解决方案是修改原始源代码:

负责警告的原始代码

('WARNING: problems with charset recognition', "'\x1b'")

在 iptcinfo.py 文件的第 971 行。

LOG.warn('problems with charset recognition %s', repr(temp))

你可以 fork 原始的 github repo 并简单地把它注释掉

#LOG.warn('problems with charset recognition %s', repr(temp))

然后

#Uninstall the original installation
pip uninstall iptcinfo
#Do pip install from your own fork. e.g.:
pip install git+git://github.com/Sulli/iptcinfo.git

【讨论】:

    猜你喜欢
    • 2013-01-05
    • 1970-01-01
    • 2018-10-06
    • 2020-11-18
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多