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
# 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.