You can do this by rebinding sys.stdout
:
>>> def foo():
... print('potato')
...
>>> import sys, io
>>> sys.stdout = io.StringIO()
>>> foo()
>>> val = sys.stdout.getvalue()
>>> sys.stdout = sys.__stdout__ # restores original stdout
>>> print(val)
potato
For a nicer way to do it, consider writing a context manager. If you're on Python 3.4+, it's already been written for you.
>>> from contextlib import redirect_stdout
>>> f = io.StringIO()
>>> with redirect_stdout(f):
... foo()
...
>>> print(f.getvalue())
potato
In the case that you are able to modify the function itself, it may be cleaner to allow a dependency injection of the output stream (this is just a fancy way of saying "passing arguments"):
def foo(file=sys.stdout):
print('potato', file=file)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…