Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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