python 的 print() 函数实际上调用的是 sys.stdout()

那么可以使用以下脚本将print()同时输出到控制台和文件中。注意,只有print()中的内容是str时,才有效。

import datetime
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--ppath', type=str, required=False, default=".", help="Data directory")
args = parser.parse_args()

def make_print_to_file(path='./'):
    '''
    path, it is a path for save your log about fuction print
    example:
    use  make_print_to_file()   and the   all the information of funtion print , will be write in to a log file
    :return:
    '''

    class Logger(object):
        def __init__(self, filename="Default.log", path="./"):
            self.terminal = sys.stdout
            self.log = open(os.path.join(path, filename), "a", encoding='utf8', )

        def write(self, message):
            self.terminal.write(message)
            self.log.write(message)

        def flush(self):
            pass

    fileName = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
    sys.stdout = Logger(fileName + '.log', path=path)

    # print(fileName.center(60, '*'))
if not os.path.exists(f'{args.ppath}/logs/'):
    os.makedirs(f'{args.ppath}/logs/')
make_print_to_file(path=f'{args.ppath}/logs/')
打赏作者

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

CAPTCHA