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

Dani AI

Generated

The reason your logfile only contains output when --vmode is set is that the program only calls your test functions inside the if args.verbose: branch. Two straightforward fixes:

  • Keep your functions running normally but make sys.stdout a "tee" that always writes to the file and only echoes to the console when --vmode is true.
  • Or switch to Python's logging and attach a FileHandler always plus a StreamHandler only when verbose.

Minimal change (tee stdout; use sys.__stdout__ to avoid recursion, implement flush, and restore on exit):

import sys

class Tee(object):
    def __init__(self, filename, to_console=True):
        self.console = sys.__stdout__ if to_console else None
        self.file = open(filename, 'a')

    def write(self, msg):
        if self.console:
            self.console.write(msg)
        self.file.write(msg)

    def flush(self):
        if self.console:
            self.console.flush()
        self.file.flush()

Usage pattern:

orig = sys.stdout
sys.stdout = Tee('logfile2.log', to_console=args.verbose)
try:
    # run Main1/Main2 according to --pc/--nopc (call them even if not verbose)
finally:
    sys.stdout.file.close()
    sys.stdout = orig

Recommended approach: use logging (gives levels, timestamps, easy enable/disable of console output). Attach a FileHandler unconditionally and add a StreamHandler only when args.verbose is True; then replace print calls with logger.info(...).

Troubleshooting notes: always implement flush() (prevents lost buffered output), close the file in a finally block, prefer sys.__stdout__ when writing to the real terminal, and consider from __future__ import print_function if you need Python 2/3 compatibility.

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.