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设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

OPENCV去除小连通区域,去除孔洞的实例讲解

OPENCV去除小连通区域,去除孔洞的实例讲解

一、对于二值图,0代表黑色,255代表白色。去除小连通区域与孔洞,小连通区域用8邻域,孔洞用4邻域。 函数名字为:void RemoveSmallRegion(Mat &Src, Ma...

Python/Django后端使用PIL Image生成头像缩略图

本文实例为大家分享了Python/Django后端使用PIL Image生成头像缩略图的具体代码,供大家参考,具体内容如下 import os from django.views.g...

Python 实现遥感影像波段组合的示例代码

Python 实现遥感影像波段组合的示例代码

最近要做个遥感相关的小系统,需要波段组合功能,网上找了可以使用ArcGIS安装时自带的arcpy包,但是Python3.7不能使用现有ArcGIS10.2版本,也不想再装其他版本,所以只...

Python判断列表是否已排序的各种方法及其性能分析

声明 本文基于Python2.7语言,给出判断列表是否已排序的多种方法,并在作者的Windows XP主机(Pentium G630 2.7GHz主频2GB内存)上对比和分析其性能表现...

Python学习笔记之For循环用法详解

本文实例讲述了Python学习笔记之For循环用法。分享给大家供大家参考,具体如下: Python 中的For循环 Python 有两种类型的循环:for 循环和 while 循环。fo...