Python:禁用iptcinfo警告

时间:2018-05-18 09:10:07

标签: python warnings iptc

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

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

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

我的代码很简单:

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

3 个答案:

答案 0 :(得分:1)

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)

修改:要进行问题排查,请参阅以下内容,了解每个记录器的级别:

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

答案 1 :(得分: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)

并且效果很好

No Print

答案 2 :(得分:0)

首先,我认为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