Python: 禁用 iptcinfo 警告提示

4
我正在使用iptcinfo Python 模块来获取一张图片的元数据,但它向我抛出了很多(无用的)警告,例如:('WARNING: problems with charset recognition', "'\x1b'")。这是什么意思,如何去除这些警告(或者防止它们发生),因为这些警告似乎对我的代码没有任何影响?
我的代码十分简单:
import iptcinfo
iptc = iptcinfo.IPTCInfo("DSC05647.jpg") 

你使用的 iptcinfo 版本是什么?如果不知道,请尝试打印 iptcinfo.__version__ 查看。 - mouche
@mouche 我正在使用 iptcinfo 版本 1.9.5-6。 - Sulli
1
这是我回答所指的版本。请查看我的编辑以获取调试记录器和级别。 - mouche
@mouche 谢谢,但是这个 man 页面超出了我的能力范围。你能重现我的问题吗? - Sulli
1
我还没有尝试过,但我认为问题可能与图像元数据相关的信息有关。你的图像是Unicode格式,这就是为什么库会出现问题的原因。我想让你尝试Python 3的原因是,它可以让我们知道是否已经解决了这个问题。Python 3默认使用Unicode,所以如果我们知道它在Python 3中可以工作,那么我们可以确定这是一个Unicode/str转换问题,而不是Python 2的问题。所以如果你能在Python 3中尝试一下,那么就可以更快地找到一些解释了。 - Tarun Lalwani
显示剩余6条评论
3个回答

3

代码中的这一行 似乎是导致警告出现的原因:

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

您看到此消息是因为Python的日志记录模块的默认日志级别为“warning”(警告)。在您的代码中,您可以修改库的记录器的日志级别变高,这样就不会看到警告。具体方法请参考 日志级别
import logging
iptcinfo_logger = logging.getLogger('iptcinfo')
iptcinfo_logger.setLevel(logging.ERROR)

编辑:用于故障排除,以下是一个代码片段,可以查看每个记录器的级别:

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

我刚刚尝试了那段代码,但仍然收到了警告。 - Sulli
你在运行函数之前导入 iptcinfo 吗? - mouche
查看Python的logging模块,以更好地调试活动的记录器及其所处的日志级别。 - mouche
很棒的答案,对我在IPTCInfo3-2.1.4上也起作用了。 - nealmcb
另请参阅我的问题记录,了解该模块似乎在首次解析字符集时出现错误的详细信息:WARNING: problems with charset recognition (b'\x1b') from parsing Iptc.Envelope.CharacterSet incorrectly · Issue #32 · jamesacampbell/iptcinfo3 - nealmcb
显示剩余2条评论

2
问题在于你使用的模块执行了一些超出你对模块功能的期望的操作。
print (
       'WARNING: problems with charset recognition',
      repr(temp))

有些东西不能直接禁用。但是 Stack Overflow 上有很多好的帖子可以教你如何实现相同的功能。

在 Python 中消除函数的标准输出,而不破坏 sys.stdout 和恢复每个函数调用

抑制 Python 中的 print 调用

因此将它们结合起来

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安装的代码存在一些差异。可能是包最近没有被推送或者使用的不是最新的代码。 - Tarun Lalwani

1
首先,我认为iptcinfo应该可以与Python 2完美配合使用。
另一个解决方案是修改原始源代码:
负责警告的原始代码
('WARNING: problems with charset recognition', "'\x1b'")

在 iptcinfo.py 文件的第 971 行。

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

你可以复制原始的 Github 仓库并将其简单地注释掉。
#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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接