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?

martineau
  • 119,623
  • 25
  • 170
  • 301
WeaselFox
  • 7,220
  • 8
  • 44
  • 75
  • 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.. – Torxed Feb 20 '14 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` – WeaselFox Feb 20 '14 at 14:19
  • 1
    When using Python3, you could override the `print` function and have it collect the data somewhere else. – tobias_k Feb 20 '14 at 14:20
  • this is python 2.7 let me retag.. – WeaselFox Feb 20 '14 at 14:21
  • That's true, you can do `sys.stdout = StringIO()` and print that normally ends up in `stdout` will be redirected.. – Torxed Feb 20 '14 at 14:21
  • 1
    `dis.dis()` also uses `print`; see the linked duplicate on how you could work around that. – Martijn Pieters Feb 20 '14 at 14:21
  • If the library is implemented in C or starts a child process then you need to redirect at C level. See [How do I prevent a C shared library to print on stdout in python?](http://stackoverflow.com/q/5081657/4279) – jfs Mar 12 '14 at 11:25

1 Answers1

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'
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • I could use this solution.. not very elegant though. thanks – WeaselFox Feb 20 '14 at 14:26
  • 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()". – ccy Apr 11 '19 at 06:43