import contextlib
import sys
def your_task():
print("The test !")
@contextlib.contextmanager
def close_stdout(redirect_to="/var/log/your.log"):
raw_stdout = sys.stdout
file = open(redirect_to, "a+")
sys.stdout = file
yield
sys.stdout = raw_stdout
file.close()
with close_stdout(redirect_to="./test.log"):
your_task()
Forked from cleiveliu/Python-context-manager-example.md
Created
August 13, 2021 03:19
-
-
Save GoodManWEN/e51ec7e765e194856e20cf9d74758e49 to your computer and use it in GitHub Desktop.
Python context manager example
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment