Skip to content

Instantly share code, notes, and snippets.

@cleiveliu
Last active August 13, 2021 03:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cleiveliu/ed5ecfc7dc074a85ccf3d11cd38ea827 to your computer and use it in GitHub Desktop.
Save cleiveliu/ed5ecfc7dc074a85ccf3d11cd38ea827 to your computer and use it in GitHub Desktop.
Python context manager example

source

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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment