0

I have written some code just to practice verbosity in python. Verbosity is embedded by means of the ArgumentParser module. However, I'd also like to write the stdout to file also when verbosity is disabled:

#!/usr/bin/python                                                               
import sys

def printable1():
    print "1"

def printable2():
    print "2"

def printable3():
    print "3"

def Main1():
    printable1()
    printable2()

def Main2():
    printable2()
    printable3()

class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open("logfile2.log", "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)


if __name__ == "__main__":
    from argparse import ArgumentParser

    parser = ArgumentParser(description='PC Test',version="1.0")
    parser.add_argument('--nopc',action='store_true', help='Do not perform test on the PC')
    parser.add_argument('--pc', action='store_true', help='Do perform test on the PC')

    # VERBOSITY 
    parser.add_argument('--vmode', dest='verbose', action='store_true',
                        help='Enable printing of status messages to stdout.')

    args = parser.parse_args()

    sys.stdout = Logger()

    if args.verbose:
        if args.pc:       
            Main1()
        elif args.nopc:
            Main2()
        else:
            Main1()
            Main2()  

This code writes the stdout to file only when verbosity is enabled with the --vmode argument. Can you help me to find a solution?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user2457613
  • 61
  • 1
  • 6
  • I've cleaned up your code to only include relevant lines (removing all the comment-out code, extra whitespace and unused imports); it makes it much easier for us to help you if your samples only contain the code needed to reproduce the problem. – Martijn Pieters Mar 01 '14 at 18:45
  • thank you Martjin, i'll take care of it in the next future. I apologize again. – user2457613 Mar 01 '14 at 20:01

1 Answers1

1

Instead of reinventing the wheel, you could use the logging module to handle printing to terminal and writing into a file. The verbosity part is still up to you:

import logging
import logging.handlers
log = logging.getLogger(__name__)
log.addHandler(logging.StreamHandler())  # Prints to console.
log.addHandler(logging.handlers.RotatingFileHandler('logfile2.log'))
log.setLevel(logging.INFO)  # Set logging level here.

Since now on, you can use that regular log object to perform logging in your script, and the entries will be both sent to console and to the file:

log.info('test')
log.warning('test')

Also, I recommend using ConfigDict to handle registering loggers and handlers - a more declarative alternative to the way above (you'll still need to instantiate log object as above).

Maciej Gol
  • 15,394
  • 4
  • 33
  • 51