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自定义进程池。分享给大家供大家参考,具体如下: 代码说明一切: #encoding=utf-8 #author: walker #date: 2014-05...

讲解Python中if语句的嵌套用法

 可能有这样一种情况,当你想检查其他条件后一个条件解析为真。在这种情况下,可以使用嵌套的if结构。 在嵌套的 if 语句结构,可以在一个 if... elif... else...

python读写csv文件方法详细总结

python提供了大量的库,可以非常方便的进行各种操作,现在把python中实现读写csv文件的方法使用程序的方式呈现出来。 在编写python程序的时候需要csv模块或者pandas模...

python3中property使用方法详解

本文实例为大家分享了python3中的property使用方法,供大家参考,具体内容如下 property属性 定义 一个可以使实例方法用起来像实例属性一样的特殊关键字,可以对应于某个方...

Python实现注册、登录小程序功能

Python实现注册、登录小程序功能

主要实现功能 1、用户输入用户名,在用户名文件中查找对应的用户,若无对应用户名则打印输入错误 2、用户名输入正确后,进行密码匹配。输入密码正确则登录成功,否则重新输入。 3、连续输错三次...