Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture print output of another module?

Tags:

python

stdout

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?

like image 728
waka-waka-waka Avatar asked Apr 02 '14 20:04

waka-waka-waka


People also ask

How do you print output in Python?

To capture stdout output from a Python function call, we can use the redirect_stdout function. to call redirect_stdout with the f StringIO object. Then we call do_something which prints stuff to stdout. And then we get the value printed to stdout with f.

How do you assign a print output to a variable in Python?

So print() also a function with the return value with None . So the return value of python function is None . But you can call the function(with parenthesis ()) and save the return value in this way. So the var variable has the return value of some_function() or the default value None .

Can Python module contains print?

Yes. They're built-in functions (or in the case of list , a built-in class).


2 Answers

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.

like image 108
AlanSE Avatar answered Sep 18 '22 21:09

AlanSE


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
like image 22
drodri Avatar answered Sep 21 '22 21:09

drodri