Access the printed output of a function call

2019-02-19 03:22发布

问题:

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

回答1:

As @JimDeville commented, you can swap 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!