Python information output to console and file at the same time

Source: Internet
Author: User

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‘)
    • 1
    • 2
    • 3
    • 4
    • 5
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")的方式写入文件
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.