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

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

相关文章

Python实现点阵字体读取与转换的方法

Python实现点阵字体读取与转换的方法

点阵字体是指根据文字的像素点来显示的字体,效果如下: 使用Python读取并显示的过程如下: 根据中文字符获取GB2312编码 通过GB2312编码计算该汉字在点阵字库中的区位和码位...

pandas将DataFrame的列变成行索引的方法

pandas提供了set_index方法可以将DataFrame的列(多列)变成行索引,通过reset_index方法可以将层次化索引的级别会被转移到列里面。 1、DataFrame的s...

对Python 除法负数取商的取整方式详解

python除法负数商的取整方式与C++不同 python: 5 / -2 = -3 若想和C++行为相同,可以使用 int(operator.truediv(num1, num2...

python输出数组中指定元素的所有索引示例

python输出数组中指定元素的所有索引示例

如下所示,代码为: array也可直接使用上面代码。测试如下: 以上这篇python输出数组中指定元素的所有索引示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多...

python访问mysql数据库的实现方法(2则示例)

本文实例讲述了python访问mysql数据库的实现方法。分享给大家供大家参考,具体如下: 首先安装与Python版本匹配的MySQLdb 示例一 import MySQLdb co...