4

Part of my script calls a function from (let's call it foo) another module (written by someone else a long time ago, and I don't want to start modifying it now).
foo writes interesting things to stdout (but returns None), in part, by calling other functions as well. I want to access these interesting things that foo writes to stdout.

As far as I know, subprocess is meant to call commands that I would normally call from the command line. Is there an equivalent for python functions that I would call from my script?

I'm on python2.7, if it matters

inspectorG4dget
  • 97,394
  • 22
  • 128
  • 222
  • I don't know Python well enough, but with Ruby, I would do this by changing stdout to a buffer that I control, calling the function, restoring stdout, and then manipulating the data in the buffer as needed. – Jim Deville Jan 20 '13 at 08:19

1 Answers1

4

As @JimDeville commented, you can swap stdout:

#!python2.7
import io
import sys

def foo():
    print 'hello, world!'

capture = io.BytesIO()
save,sys.stdout = sys.stdout,capture
foo()
sys.stdout = save
print capture.getvalue()

Output:

hello, world!

Python 3 version uses io.StringIO instead due to stdout expected to be a Unicode stream:

#!python3
import io
import sys

def foo():
    print('hello, world!')

capture = io.StringIO()
save,sys.stdout = sys.stdout,capture
foo()
sys.stdout = save
print(capture.getvalue())
Mark Tolonen
  • 132,868
  • 21
  • 152
  • 208