访问函数调用的打印输出
问题内容:
我的脚本的一部分从foo
另一个模块(很久以前由其他人编写,而我现在不想开始对其进行修改)中调用一个函数(简称为)。
foo
还通过调用其他函数来写一些有趣的东西stdout
(但返回None
)。我想访问这些是有趣的事情foo
写到stdout
。
据我所知,subprocess
它的作用是调用通常在命令行中调用的命令。我可以从脚本中调用python函数吗?
我在使用python2.7,如果有关系
问题答案:
正如@JimDeville所说,您可以交换标准输出:
#!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()
输出:
hello, world!
io.StringIO
由于stdout
预期是Unicode流,因此使用了Python 3版本:
#!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())