从“print"获取输出在函数内部 [英] Getting output from "print" inside a function
本文介绍了从“print"获取输出在函数内部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用一个函数库,其中一些函数可以打印我需要的数据:
def func():打印数据"
如何调用这个函数,把打印出来的数据变成字符串?
解决方案
如果你不能改变这些功能,你需要重定向 sys.stdout
:
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?
解决方案
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'
这篇关于从“print"获取输出在函数内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文