11

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

Matan
  • 281
  • 3
  • 7

1 Answers1

9

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
Giampaolo Rodolà
  • 12,488
  • 6
  • 68
  • 60
elcr
  • 101
  • 1
  • 6
  • Is it change the all program sdtout? because I have some threads in the same process.. – Matan May 28 '17 at 14:03
  • It does more or less the same thing as `redirect_stdout` from Python 3's `contextlib`, whose docs [say it is not suitable for threaded applications](https://docs.python.org/3/library/contextlib.html?highlight=contextlib.redirect_stdout#contextlib.redirect_stdout). I haven't tested it, but it should redirect `stdout` globally for all threads. I'm not aware of any way to redirect it in only the current thread. – elcr May 28 '17 at 20:07