我有这个脚本,我现在想要将输出放在屏幕上并放入日志文件中。有谁可以帮我解决这个问题?
PS:不要介意我的调试行plz
THX
#!/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)
答案 0 :(得分:2)
您可以使用子进程进程的logging模块和communic()方法:
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 )
这将记录到stdout和文件。
您甚至可以添加更多处理程序,例如流处理程序
logging.addHandler( logging.StreamHandler( someStreamlikeObject ) )
另一件事: 除非必要,否则不应使用shell = True,因为它不安全并带来一些技术条件(请参阅子流程文档)。上面的代码以不使用shell = True的方式进行了更改。