arty.net 0 Newbie Poster

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                                                               

from optparse import OptionParser

from argparse import ArgumentParser

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)

#te = open('./logfiles.txt','w')  # File where you need to keep the logs

#class Unbuffered:

        #def __init__(self, stream):

            #self.stream = stream

        #def write(self, data):

            #self.stream.write(data)
            #self.stream.flush()
            #te.write(data)    # Write the data of stdout here to a text file as well

if __name__ == "__main__":

        from argparse import ArgumentParser
        import logging



        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.')

        #parser.add_argument('-q', dest='verbose', action='store_false', default=False,
                          #help='Disable 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. May you help me to find a solution ? Thanks in advance.

Regards, Arturo

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.