Suppress output to stdout/stderr in InteractiveInterpreter
Jerry Hill
malaclypse2 at gmail.com
Wed Apr 14 23:14:13 EDT 2010
On Wed, Apr 14, 2010 at 9:03 PM, Dave W. <evadeflow at gmail.com> wrote:
> I thought I could get away with import print_function from __future__
> (see example code below), but my re-pointed print function never gets
> called.
-snip-
> def __enter__(self):
> print = self.printhook
That redefines the print function local to __enter__. You need to
change the global value of print.
from __future__ import print_function
from contextlib import contextmanager
def printhook(obj, *args, **kwargs):
__builtins__.print('['+obj+']', *args, **kwargs)
@contextmanager
def local_printhook():
print = printhook
yield
print = __builtins__.print
@contextmanager
def global_printhook():
global print
print = printhook
yield
print = __builtins__.print
with local_printhook():
print("Test 1")
with global_printhook():
print("Test 2")
>>> ================================ RESTART ================================
>>>
Test 1
[Test 2]
>>>
More information about the Python-list
mailing list