Access the printed output of a function call

十年热恋 提交于 2019-12-01 07:09:34

问题


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!


来源:https://stackoverflow.com/questions/14422797/access-the-printed-output-of-a-function-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!