Python脚本,登录到屏幕和fi

2024-04-19 13:47:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个脚本,现在我想把输出放在屏幕上并放到一个日志文件中。有谁能帮我做这件事吗?在

PS:不介意我的调试行plz

泰铢

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

Tags: importaddparserurloutputargparsehelpargs
1条回答
网友
1楼 · 发布于 2024-04-19 13:47:26

您可以使用子流程流程的logging模块和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 )

这将记录到stdout和一个文件。在

您甚至可以添加更多的处理程序,例如

^{pr2}$

还有一件事: 除非有必要,否则不应使用shell=True,因为它不安全并且会带来一些技术条件(请参阅子流程文档)。以上代码的更改方式不使用shell=True。在

相关问题 更多 >