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

来源:互联网 发布:usb无线网卡linux驱动 编辑:程序博客网 时间:2024/05/01 19:23

先把代码贴出来,在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_usageAuthor:     CrifanVerison:    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()

使用logging–成功

在上面的代码中,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

修改sys.stdout–失败

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

使用tee命令–成功

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

python myscrip.py | tee -a mylog.log

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

多个py文件的logging输出到同一个日志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中了。

0 0
原创粉丝点击