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

相关文章

Python3字符串encode与decode的讲解

大家好,很久没更新了,也是年底了最近比较忙,同时也在研究python的其他内容,毕竟是python小白,自学道路艰难。 好了今天和大家一起探讨下python3编码过程中对的一些转码事宜。...

Python的Django框架使用入门指引

Python的Django框架使用入门指引

 前言 传统 Web 开发方式常常需要编写繁琐乏味的重复性代码,不仅页面表现与逻辑实现的代码混杂在一起,而且代码编写效率不高。对于开发者来说,选择一个功能强大并且操作简洁的开发...

对Pandas MultiIndex(多重索引)详解

创建多重索引 In [16]: df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=ind...

Pycharm+Python+PyQt5使用详解

Pycharm+Python+PyQt5使用详解

1,打开cmd安装PyQt5 pip install pyqt5 2,PyQt5不再提供Qt Designer等工具,所以需要再安装pyqt5-tools pip instal...

Python中表达式x += y和x = x+y 的区别详解

前言 本文主要给大家介绍的是关于Python中表达式x += y和x = x+y 区别的相关内容,分享出来供大家参考学习,下面来看看详细的介绍: 直接看下面代码: x +=y In...