Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting output from "print" inside a function [duplicate]

Im using a library of functions that some of them print data I need:

def func():
   print "data"

How can I call this function and get the printed data into a string?

like image 510
WeaselFox Avatar asked Feb 20 '14 14:02

WeaselFox


People also ask

Can you print from within a function?

Answers. You can't use a print inside a FUNCTION.

What is the difference between printing inside a function and returning a result?

print just shows the human user a string representing what is going on inside the computer. The computer cannot make use of that printing. return is how a function gives back a value. This value is often unseen by the human user, but it can be used by the computer in further functions.

How do you repeat a Output in Python?

In Python, we utilize the asterisk operator to repeat a string. This operator is indicated by a “*” sign. This operator iterates the string n (number) of times. The “n” is an integer value.


1 Answers

If you can't change those functions, you will need to redirect sys.stdout:

>>> import sys
>>> stdout = sys.stdout
>>> import StringIO
>>> s = StringIO.StringIO()
>>> sys.stdout = s
>>> print "hello"
>>> sys.stdout = stdout
>>> s.seek(0)
>>> s.read()
'hello\n'
like image 145
Tim Pietzcker Avatar answered Oct 11 '22 07:10

Tim Pietzcker