mortuzahasan mortuzahasan - 2 months ago 16
Python Question

Python - writing terminal output to file

i have different functions which is giving string and text output in the terminal during excecution of the function. the command i have used is sys.stdout.write

in one of the function i am creating a file and calling those functions mentioned above. when running this function i need to write all the sys.output.write(output from different function)in the file as well along with terminal.

Please help me to implement this

sample code is like

def func1():
sys.stdout.write('A')
sys.stdout.write('B')

def func2():
sys.stdout.write('C')
sys.stdout.write('D')
def main():
fileName=open("log.txt","W+")
func1()
func2()
--------------------
# need output ABCD both in terminal and write in logfile as well
# unfortunately cannot change anything in func1() and func2()

Answer

Use a context manager to create a wrapper that writes to a file and stdout:

class Tee(object):
    def __init__(self, log_file_name, stdout):
        self.log_file_name = log_file_name
        self.stdout = stdout

    def __enter__(self):
        self.log_file = open(self.log_file_name, 'a', 0)
        return self

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.log_file.close()

    def write(self, data):
        self.log_file.write(data)
        self.stdout.write(data)
        self.stdout.flush()

def main():
    with Tee('log.txt', sys.stdout) as sys.stdout:
        func1()
        func2()

Don't forget to flush stdout after each write as it is buffered.