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

python编程中,每每须要将结果用print等输出,若是但愿输出既能够显示到IDE的屏幕上,也能存到文件中(如txt)中,该怎么办呢?python


方法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和文件名this

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()) # 将记录在文件中的结果输出到屏幕
相关文章
相关标签/搜索