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


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()) # 将记录在文件中的结果输出到屏幕


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM