9

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?

7
  • 3
    You can't... Try return "data" which is the only way to go. Unless you want to catch the output of another python script, then you can use x = subprocess.Popen("python script.py", shell=True") and then x.stdout.read(). Might (and i mean might.. only thought about it for a second) be able to use eval() to call the function and there catch the output.. But wouldn't reccomend it.. Commented Feb 20, 2014 at 14:18
  • yes... well I want to avoid changing the library code. If ther really is no way, I will copy paste into my code and use return Commented Feb 20, 2014 at 14:19
  • 1
    When using Python3, you could override the print function and have it collect the data somewhere else. Commented Feb 20, 2014 at 14:20
  • this is python 2.7 let me retag.. Commented Feb 20, 2014 at 14:21
  • 1
    dis.dis() also uses print; see the linked duplicate on how you could work around that. Commented Feb 20, 2014 at 14:21

1 Answer 1

10

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'
Sign up to request clarification or add additional context in comments.

2 Comments

I could use this solution.. not very elegant though. thanks
If you want to use it Python3, you should change the 3rd line as "from io import StringIO", and the 4th line as "s = StringIO()".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.