Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

python - How to capture print output of another module?

I was wondering if this is possible in python:

# module1
def test():
    print('hey')

# module2
import module1

module1.test() # prints to stdout

Without modifying module1 is there any way to wrap this in module2 so that I can capture the print('hey') inside a variable? Apart from running module1 as a script?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...