python将print输出的信息保留到日志文件中

yipeiwu_com5年前Python基础

具体代码如下所示:

import sys
import os
import sys
import io
import datetime
def create_detail_day():
 '''
 :return:
 '''
 # 年-月-日
 # daytime = datetime.datetime.now().strftime('day'+'%Y-%m-%d')
 # 年_月_日
 daytime = datetime.datetime.now().strftime('day'+'%Y_%m_%d')
 # 时:分:秒
 # hourtime = datetime.datetime.now().strftime("%H:%M:%S")
 # hourtime = datetime.datetime.now().strftime('time' + "%H_%M_%S")
 detail_time = daytime
 # print(daytime + "-" + hourtime)
 # detail_time = daytime + "__" + hourtime
 return detail_time
def make_print_to_file(path='./'):
 '''
  example:
 use make_print_to_file() , and the all the information of funtion print , will be write in to a log file
 :param path: the path to save print information
 :return:
 '''
 class Logger(object):
  def __init__(self, filename="Default.log", path="./"):
   sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
   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
 sys.stdout = Logger(create_detail_day() + '.log', path=path)
 print(create_detail_time().center(60,'*'))
if __name__ == '__main__':
  make_print_to_file(path="/home/log/")
  print('explanation'.center(80, '*'))
  info1 = '从大到小排序'
  info2 = ' sort the form large to small'
  print(info1)
  print(info2)
  print('END: explanation'.center(80, '*'))

总结

以上所述是小编给大家介绍的python将print输出的信息保留到日志文件中,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

Ubuntu 16.04 LTS中源码安装Python 3.6.0的方法教程

前提 官网上提供了 Mac 和 Windows 上的安装包和 Linux 上安装需要的源码。 下载地址如下: https://www.python.org/downloads/relea...

Python实现合并字典的方法

本文实例讲述了Python实现合并字典的方法。分享给大家供大家参考。具体实现方法如下: # 将两个字典合并 #!/usr/bin/python def adddict(dict1,d...

理解python多线程(python多线程简明教程)

对于python 多线程的理解,我花了很长时间,搜索的大部份文章都不够通俗易懂。所以,这里力图用简单的例子,让你对多线程有个初步的认识。 单线程   在好些年前的MS-DOS时代,操作系...

python系列 文件操作的代码

python系列 文件操作的代码

核心代码 import numpy as np import os,sys #获取当前文件夹,并根据文件名 def path(fileName): p=sys.path[0]+'...

python ChainMap的使用和说明详解

ChainMap是Python collections模块中的一个成员,它用来将多个map组合到一起。Chain是链条的意思,字面意思就是把map串联到一起。 问题的背景是我们有多个字典...