Python日志中的"None"

2024-04-20 15:49:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中使用logging模块。当我在命令行中使用错误的参数调用脚本时,日志文件在某个时刻包含一个单词“None”,我不知道它来自何处。在

这是我的代码切分,我在这里日志记录.异常公司名称:

# Show script where to find blank- and viva-data / set argv

vz = glob.glob("/home/jw/cmp_blank_viva/*csv")
skript, s1, m1 = argv

# Define script-functions and logging-config

logging.basicConfig(level=logging.ERROR, filename='cmp_blank_viva.log', format='%(asctime)s:%(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')

def open_data(vz, s1, m1):

    try:

        checker = []

        for i in vz:
            if "drhot_viva_check_%s" % m1 in i:
                blank_data = csv.reader(open(i, 'r'))
                checker.append(1)
            else:
                pass

        if 1 not in checker:
            logging.exception("Could not open viva file with %s %s.\n" % (s1, m1))

        checker = []

        for i in vz:
            if "hoteldaten_%s_%s" % (m1, s1) in i:
                viva_data = csv.DictReader(open(i, 'r'), delimiter = ';')
                checker.append(1)
            else:
                pass

        if 1 not in checker:
            logging.exception("Could not open blank file with %s %s.\n" % (s1, m1))

        return blank_data, viva_data

    except IOError:
        logging.exception("Could not open file:\n " + traceback.format_exc())
    except IndexError:
        logging.exception("Could not open file:\n " + traceback.format_exc())

运行脚本(使用错误的参数)后,日志文件如下所示:

^{pr2}$

有什么想法吗?在


Tags: indataifloggingexceptioncheckernotopen
1条回答
网友
1楼 · 发布于 2024-04-20 15:49:28

您使用的是logging.exception(),当时没有异常

logging.exception("Could not open viva file with %s %s.\n" % (s1, m1))

因为没有异常要记录,所以添加了None。在这里使用logging.error()只记录一条消息:

^{pr2}$

您不需要插入字符串元素,logging会在需要时为您执行此操作。我还删除了\n新行,这也是为您添加的。在

在其他地方,当位于异常处理程序中时,您将手动包括异常:

logging.exception("Could not open file:\n " + traceback.format_exc())

您不需要手动附加回溯,logging.exception()会为您处理这个问题,并包含正确格式的回溯。在

只需记录消息,无需更多:

logging.exception("Could not open file")

^{} documentation

Exception info is always added to the logging message. This method should only be called from an exception handler.

Bold emphasis我的;您在异常处理程序之外使用它,因此没有异常可供记录。在

它通过为您设置^{} keyword argument来实现此目的:

  • exc_info* which, if it does not evaluate as false, causes exception information to be added to the logging message. If an exception tuple (in the format returned by sys.exc_info()) is provided, it is used; otherwise, sys.exc_info() is called to get the exception information.

相关问题 更多 >