访问函数调用的打印输出

4 投票
1 回答
744 浏览
提问于 2025-04-17 13:17

我的脚本中有一部分需要调用一个来自其他模块的函数(我们叫它 foo),这个模块是很久以前别人写的,我现在不想去改动它。
foo 会把一些有趣的内容输出到 stdout(标准输出),但它返回的结果是 None,而且它还会调用其他函数来完成这个输出。

我想获取 foo 输出到 stdout 的那些有趣的内容。

据我所知,subprocess 是用来调用我通常在命令行中输入的命令的。那么,有没有类似的方式可以用来调用我在脚本中需要用到的 python 函数呢?

我使用的是 python2.7,如果这有影响的话。

1 个回答

4

正如@JimDeville所说,你可以交换标准输出(stdout):

#!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!

Python 3版本使用了io.StringIO,这是因为stdout需要处理Unicode流:

#!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())

撰写回答