分享一个python写日志的函数

在回溯Phylophlan\text{Phylophlan}Phylophlan源码时,发现一个写日志的函数非常好用,书写起来非常美观:
直接复制-粘贴就好啦~

import sys

def info(s, init_new_line=False, exit=False, exit_value=0):
    if init_new_line:
        sys.stdout.write('\n')

    sys.stdout.write('[info] {}'.format(s))
    sys.stdout.flush()

    if exit:
        sys.exit(exit_value)

具体用法示例如下:

for i in range(5):
    info("Current output:{}\n".format(i))
info("Loop end..\n")

返回结果如下:

[info] Current output:0
[info] Current output:1
[info] Current output:2
[info] Current output:3
[info] Current output:4
[info] Loop end..

同理,也可以设置一些异常日志,只需要改一点格式即可:

def error(s, init_new_line=False, exit=False, exit_value=1):
    if init_new_line:
        sys.stderr.write('\n')

    sys.stderr.write('[error] {}\n'.format(s))
    sys.stderr.flush()

    if exit:
        sys.exit(exit_value)

示例如下:

try:
    s = 1 / 0
except Exception as e:
    error(str(e),init_new_line=1)

返回结果如下:

[error] division by zero

为了代码整洁,也是蛮拼的。大家记得多写点日志,对身体有好处。不要最后自己写的代码自己看不懂了,再慢慢debug,掉头发呀~

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐