In Python programming, you often need to output the results in print, and if you want the output to be displayed on the IDE's screen or in a file (such as TXT), what should I do?
Method 1
You can output information to a file or screen via the Log logging module. However, you may want to set the level or output of log, for the same time need to record debug error information such as more appropriate, the official tutorial recommended learning to use more standardized logger to operate.
For example, you can refer to this code from the official website.
import logginglogging.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‘)
Method 2
Output two times with print
For example, I want to output the path of the program and the file name of the program
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")的方式写入文件
Method 3
Outputs redirected two times with output redirection
Same output program path and file name
import osimport systemp=sys.stdout # 记录当前输出指向,默认是conslewith 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 information output to console and file at the same time