subprocess - Python script, log to screen and to file -


i have script, , want put output on screen , log file. can me on how this?

ps: don't mind debug lines plz

thx

#!/usr/bin/python   import os import subprocess import sys import argparse subprocess import popen, pipe, call  parser = argparse.argumentparser() parser.add_argument('-u', '--url', help='       add here url want     use. example: www.google.com') parser.add_argument('-o', '--output', help='    add here output file 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) 

you can use logging module , communicate() method of subprocess process:

import logging     import argparse import subprocess  def initlogging( args ):     formatstring = '[%(levelname)s][%(asctime)s] : %(message)s' # specify 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 logging  parser = argparse.argumentparser() parser.add_argument('-u', '--url', help='       add here url want     use. example: www.google.com') parser.add_argument('-o', '--output', help='    add here output file 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, blocking call, # stdout_string or stderr_string of type none  logging.info( stderr_string ) logging.info( stdout_string ) 

this log stdout , file.

you can add more handlers e.g. stream handlers

logging.addhandler( logging.streamhandler( somestreamlikeobject ) ) 

one other thing: should never use shell=true unless necessary because unsafe , brings technical conditions (see subprocess documentation). above code altered in way not use shell=true.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -