python capture print output of another module

爷,独闯天下 提交于 2019-11-29 10:16:06

Yes, you can. You need to take control of sys.stdout. Something like this:

import sys

stdout_ = sys.stdout #Keep track of the previous value.
sys.stdout = open('myoutputfile.txt', 'w') # Something here that provides a write method.
# calls to print, ie import module1
sys.stdout = stdout_ # restore the previous stdout.

Yes, all you need is to redirect the stdout to a memory buffer that complies with the interface of stdout, you can do it with StringIO. This works for me in 2.7:

import sys
import cStringIO

stdout_ = sys.stdout #Keep track of the previous value.
stream = cStringIO.StringIO()
sys.stdout = stream
print "hello" # Here you can do whatever you want, import module1, call test
sys.stdout = stdout_ # restore the previous stdout.
variable = stream.getvalue()  # This will get the "hello" string inside the variable

For Python 3:

# redirect sys.stdout to a buffer
import sys, io
stdout = sys.stdout
sys.stdout = io.StringIO()

# call module that calls print()
import module1
module1.test()

# get output and restore sys.stdout
output = sys.stdout.getvalue()
sys.stdout = stdout

print(output)

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!