入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

python同时标准输出和重定向到文件保存

创建时间:2015-06-04 投稿人: 浏览次数:11161

先把代码贴出来,在http://www.crifan.com/summary_python_logging_module_usage/的基础上增加了部分内容

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------------------------------------
Function:
【整理】Python中的logging模块的使用(可以实现同时输出信息到cmd终端窗口和log文件(txt)中)
http://www.crifan.com/summary_python_logging_module_usage

Author:     Crifan
Verison:    2012-11-23
-------------------------------------------------------------------------------
"""

import logging;

#-------------------------------------------------------------------------------
def loggingDemo():
    """Just demo basic usage of logging module
    """
    logging.info("You should see this info both in log file and cmd window");
    logging.warning("You should see this warning both in log file and cmd window");
    logging.error("You should see this error both in log file and cmd window");

    logging.debug("You should ONLY see this debug in log file");
    return;

#-------------------------------------------------------------------------------    
def initLogging(logFilename):
    """Init for logging
    """
    logging.basicConfig(
                    level    = logging.DEBUG,
                    format   = "LINE %(lineno)-4d  %(levelname)-8s %(message)s",
                    datefmt  = "%m-%d %H:%M",
                    filename = logFilename,
                    filemode = "w");
    # define a Handler which writes INFO messages or higher to the sys.stderr
    console = logging.StreamHandler();
    console.setLevel(logging.INFO);
    # set a format which is simpler for console use
    formatter = logging.Formatter("LINE %(lineno)-4d : %(levelname)-8s %(message)s");
    # tell the handler to use this format
    console.setFormatter(formatter);
    logging.getLogger("").addHandler(console);

def logging_stdout():
    """ modify sys.stdout
    """
    import sys
    origin = sys.stdout
    f = open("my_logging.log", "w")
    sys.stdout = f
    # ===================================
    print "Start of program"

    # 你的程序放到这里,过程中所有print到屏幕的内容都同时保存在my_logging.log里面了。
    print "Being processed..."

    print "End of program"
    # ===================================
    sys.stdout = origin
    f.close()

if __name__=="__main__":
    logFilename = "crifan_logging_demo.log"
    print "###############################################################################"
    print "Example 1: using logging"
    initLogging(logFilename)
    loggingDemo()

    print "###############################################################################"
    print "Example 2: using sys.stdout"
    logging_stdout()

在上面的代码中,Example 1成功实现了屏幕和文件的同时输出。注意console的级别是logging.INFO,而logging的级别是logging.DEBUG,故

 logging.debug("You should ONLY see this debug in log file");

并不会输出到屏幕,而只是保存到文件。logging中的级别如下,值越高级别越高。

级别 对应的值
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
NOTSET 0

Example 2也是网上大家常说的一种方法,但是经过测试,并没有成功,屏幕上并没有输出,只是保存到文件了。如果知道问题在哪,请告诉我。

在运行python脚本时加上额外的命令,如下:

python myscrip.py | tee -a mylog.log

myscrip.py中的print命令会同时输出到屏幕和保存到mylog.log文件,不过经过测试,这种方式在我的机器上好像并不是很流畅,输出一段内容后,卡住,然后过一会再输出一段内容;不过对于运行需要很长时间的程序来说,无所谓了!

from http://www.crifan.com/python_output_multiple_script_logging_into_single_log_file/

主文件设置好logging.basicConfig相关参数,配置好StreamHandler等内容后,子文件只需要导入logging模块,然后调用logging.info,logging.debug函数,即可实现将log信息,都输入到主文件的log中了。

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
  • 上一篇:没有了
  • 下一篇:没有了
未上传头像