Accessing the printed output of a function call

Part of my script is calling a function from (let's call it foo

) another module (written long ago by someone else and I don't want to change it now).
foo

writes interesting things to stdout

(but returns None

), in part by calling other functions. I want to access these interesting things that I foo

write to stdout

.

As far as I know, it is subprocess

designed to invoke 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

+3


source to share


1 answer


As @JimDeville commented, you can change stdout:

#!python2.7
import io
import sys
f=io.BytesIO()

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

save,sys.stdout = sys.stdout,f
foo()
sys.stdout = save
f.seek(0)
print f.read()

      



Output:

hello, world!

      

+4


source







All Articles