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
# need output ABCD both in terminal and write in logfile as well
# unfortunately cannot change anything in func1() and func2()
Use a context manager to create a wrapper that writes to a file and
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.