Python脚本,日志输出到屏幕和文件

3
我有这个脚本,现在想要将输出显示在屏幕上并保存到日志文件中。有谁能帮我如何做到这一点吗?
备注:请忽略我的调试行
谢谢
#!/usr/bin/python


import os
import subprocess
import sys
import argparse
from subprocess import Popen, PIPE, call

parser = argparse.ArgumentParser()
parser.add_argument('-u', '--url', help='       Add here the url you want     to use. Example: www.google.com')
parser.add_argument('-o', '--output', help='    Add here the output file for logging')
args = parser.parse_args()


print args.url
print args.output

cmd1 = ("ping -c 4 "+args.url)
cmd2 = cmd1, args.url

print cmd2
print cmd1

p = subprocess.Popen(cmd2, shell=True, stderr=subprocess.PIPE)

如果你正在运行Linux,你可以将脚本的输出直接导入到文本文件中:python yourscript.py > log.txt(如果你仍然想看到正在发生的事情,你可以使用tail -f log.txt)。 - Chrigi
也许吧,但我想让脚本来完成它。我添加了argparse以添加日志文件名。 - Bert Colemont
1个回答

3
您可以使用logging模块和subprocess进程的communicate()方法:
import logging    
import argparse
import subprocess

def initLogging( args ):
    formatString = '[%(levelname)s][%(asctime)s] : %(message)s' # specify a format string
    logLevel = logging.INFO # specify standard log level
    logging.basicConfig( format=formatString , level=logLevel, datefmt='%Y-%m-%d %I:%M:%S')
    log_file = args.output 
    fileHandler = logging.FileHandler( log_file )
    logging.root.addHandler( fileHandler ) # add file handler to logging

parser = argparse.ArgumentParser()
parser.add_argument('-u', '--url', help='       Add here the url you want     to use. Example: www.google.com')
parser.add_argument('-o', '--output', help='    Add here the output file for logging')
args = parser.parse_args()
initLogging( args )

cmd = [ "ping" , "-c" ,"4", args.url ]

p = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
stdout_string , stderr_string = p.communicate() # receive stdout, stderr, take care, this is a blocking call,
# stdout_string or stderr_string could be of type None

logging.info( stderr_string )
logging.info( stdout_string )

这将会在标准输出和文件中记录日志。

你甚至可以添加更多的处理程序,例如流处理程序,使用

logging.addHandler( logging.StreamHandler( someStreamlikeObject ) )

还有一件事: 除非必要,否则不应使用shell=True,因为它是不安全的,并且会带来一些技术问题(请参阅subprocess文档)。上述代码已经进行了修改,以不使用shell=True。


嗨,我需要加入这个代码才能让“ping”命令记录日志吗?logging.info(subprocess.Popen(cmd2, shell=True)) - Bert Colemont
抱歉,我没有完全理解问题。请参见上面的解决方案。 - Waschbaer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接