From Enrico, 1 Month ago, written in Python.
Embed
  1. # Übung 26 -- Contextmanager
  2.  
  3. from contextlib import contextmanager
  4.  
  5.  
  6. @contextmanager
  7. def myContext(filename, mode):
  8.     print("Start context")
  9.     try:
  10.         # __enter__()
  11.         print("__enter__")
  12.         aFile = open(filename, mode)
  13.         yield aFile  # return value of __enter__()
  14.     finally:
  15.         # __exit__()
  16.         print("__exit__")
  17.  
  18. with myContext("enrico.txt", 'w') as myFile:
  19.     myFile.write("Enrico\n")
  20.  
  21. import sys
  22.  
  23. class Redirect(object):
  24.     def __init__(self, aFile):
  25.         self.old_stdout = sys.stdout
  26.         self.aFile = aFile
  27.  
  28.     def __enter__(self):
  29.         sys.stdout = self.aFile
  30.  
  31.     def __exit__(self, *args): # we ignore the parameter list
  32.         sys.stdout = self.old_stdout
  33.         self.aFile.close()
  34.  
  35. with Redirect(open("enrico.txt",'w')):
  36.     print("Enrico redirected Maasch")
  37.