Jan 17, 2012 15:16
Маленькая зарисовка на тему stdout:
>>> import sys
>>> sys.stdout = open('out.txt', 'a')
>>> print 'Hello, world!' # print to file
>>> sys.stdout = sys.__stdout__
>>> print 'Hello, world!' # print to terminal
Hello, world!
Простые команды в Интернете отыскиваются труднее всего
python
Leave a comment
Comments 1
@contextlib.contextmanager
def redirect_output(stream):
""" Utility contextmanager for redirect stdout to stream
stream - file-like object (e.g. StringIO)
Usage:
>>> stream = StringIO()
>>> with redirect_output(stream):
... print("Hello")
...
>>> stream.getvalue()
'Hello\\n'
"""
old = sys.stdout
sys.stdout = stream
try:
yield
finally:
sys.stdout = old
Reply
Leave a comment