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