Nov-12-2020, 04:46 PM
You can redirect sys.stdout by defining your own context. The following code prints 'Hello there!' in file 'foo.txt' and then 'Done' to standard output. Don't close files explicitly when using the 'with' statement. They are closed automatically when the context exits
from contextlib import contextmanager import sys @contextmanager def redirect_stdout(file): old, sys.stdout = sys.stdout, file try: yield finally: sys.stdout = old def main(): with open('foo.txt', 'w') as file, redirect_stdout(file): print('Hello there!') print('Done') if __name__ == '__main__': main()That said, I don't know how the HeartRateMonitor class works, but you could consider injecting a file argument in this class instead of redirecting the global stdout.