Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

contextlib.redirect_stdout in Python2.7

I use Python2.7 and I want the function: contextlib.redirect_stdout. I mean, I want to redirect the output of specific function (not the all program). The problem is - only Python3 supports "context.redirect_stdout" and no Python2.7.

Someone know how can I use the same function in Python2.7 or to implement the same idea?

Thanks in advance

like image 351
Matan Avatar asked May 28 '17 10:05

Matan


People also ask

What is Contextlib in Python?

The contextlib module of Python's standard library provides utilities for resource allocation to the with statement. The with statement in Python is used for resource management and exception handling. Therefore, it serves as a good Context Manager.


1 Answers

Something like this should do the job if you're not worried about re-using the same context manager object.

import sys
import contextlib

@contextlib.contextmanager
def redirect_stdout(target):
    original = sys.stdout
    try:
        sys.stdout = target
        yield
    finally:
        sys.stdout = original
like image 156
elcr Avatar answered Oct 23 '22 01:10

elcr