gpt4 book ai didi

python - python 日志文件中的 "None"

转载 作者:太空狗 更新时间:2023-10-30 02:30:14 24 4
gpt4 key购买 nike

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

这是我的代码切割,我在其中执行 logging.exception:

# 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())

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

Could not open viva file with arg1 arg2.

None
Could not open blank file with arg1 arg2.

None

有什么想法吗?

最佳答案

您正在使用 logging.exception() 没有异常:

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

由于没有记录异常,因此添加了 None。在此处使用 logging.error() 仅记录一条消息:

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

您不需要插入字符串元素,logging 会在需要时为您完成。我还删除了 \n 换行符,它也是为您添加的。

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

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

您不需要手动追加回溯,logging.exception() 会为您处理这个并包括回溯,格式正确。

只记录消息,仅此而已:

logging.exception("Could not open file")

来自logging.exception() documentation :

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

大胆强调我的;您在异常处理程序之外使用了它,因此没有异常可用于记录。

它通过设置 exc_info 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.

关于python - python 日志文件中的 "None",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28302733/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com