Skip to main content
 首页 » 编程设计

Python脚本,记录到屏幕和文件

2024年10月24日13dflying

我有这个脚本,现在我想将输出显示在屏幕上并放入日志文件中。任何人都可以帮助我如何做到这一点?

PS:请不要介意我的调试行

谢谢

#!/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) 

请您参考如下方法:

您可以使用子进程的日志记录模块和 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,因为它不安全并且会带来一些技术条件(请参阅子流程文档)。上面的代码以不使用 shell=True 的方式进行了更改。