码迷,mamicode.com
首页 > 编程语言 > 详细

python 信息同时输出到控制台与文件

时间:2017-12-23 21:45:30      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:参考   class   信息   and   debug   with   代码   readlines   his   

python编程中,往往需要将结果用print等输出,如果希望输出既可以显示到IDE的屏幕上,也能存到文件中(如txt)中,该怎么办呢?


方法1

可通过日志logging模块输出信息到文件或屏幕。但可能要设置log的level或输出端,对于同时需要记录debug error等信息的较为合适,官方教程推荐学习用更规范的logger来操作。 
例如,可参考来自官网的这段代码。

import logging
logging.basicConfig(filename=‘log_examp.log‘,level=logging.DEBUG)
logging.debug(‘This message should go to the log file‘)
logging.info(‘So should this‘)
logging.warning(‘And this, too‘)
  • 1
  • 2
  • 3
  • 4
  • 5

方法2

利用print输出两次 
比如这里我想输出程序的path和程序的文件名

import os
# 第一句输出到consle:
print("filepath:",__file__,"\nfilename:",os.path.basename(__file__))
# 第二句输出到txt:
with open("outputlog.txt","a+") as f:
    print("filepath:",__file__,
    "\nfilename:",os.path.basename(__file__))
    #当然 也可以用f.write("info")的方式写入文件
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

方法3

利用输出重定向输出两次 
同样输出程序path和文件名

import os
import sys

temp=sys.stdout # 记录当前输出指向,默认是consle

with open("outputlog.txt","a+") as f:
    sys.stdout=f   # 输出指向txt文件
    print("filepath:",__file__,
    "\nfilename:",os.path.basename(__file__))
    print("some other information")
    print("some other")
    print("information")
    sys.stdout=temp # 输出重定向回consle
    print(f.readlines()) # 将记录在文件中的结果输出到屏幕

python 信息同时输出到控制台与文件

标签:参考   class   信息   and   debug   with   代码   readlines   his   

原文地址:http://www.cnblogs.com/to-creat/p/8094235.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!