Nov-13-2020, 09:40 AM
For the first question, you still have the error because you must not indent the
If you want to print simultaneously to the file and to the console, here is an updated version
@contextmanager def redirect_stdout(file): ...Don't write this definition in a class, write it at module level outside of any class and without indentation.
If you want to print simultaneously to the file and to the console, here is an updated version
from contextlib import contextmanager import sys @contextmanager def redirect_stdout(file): old, sys.stdout = sys.stdout, file try: yield finally: sys.stdout = old class FileTee: """Stores a sequence of file objects to allow printing to several files at a time""" def __init__(self, ifile): self.ifile = list(ifile) def write(self, s): for f in self.ifile: f.write(s) def main(): with open('foo.txt', 'w') as file, redirect_stdout( FileTee([sys.stdout, file])): print('Hello there!') print('Done') if __name__ == '__main__': main()