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?