I don't want to be responsible for modifying sys.stdout
and then restoring it to its previous values. The above answers don't have any finally:
clause, which can be dangerous integrating this into other important code.
https://docs.python.org/3/library/contextlib.html
import contextlib, io
f = io.StringIO()
with contextlib.redirect_stdout(f):
module1.test()
output = f.getvalue()
You probably want the variable output
which is <class 'str'>
with the redirected stdout.
Note: this code is lifted from the official docs with trivial modifications (but tested). Another version of this answer was already given to a mostly duplicated question here: https://stackoverflow.com/a/22434594/1092940
I leave the answer here because it is a much better solution than the others here IMO.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…