问题描述
我的脚本的一部分从(我们称之为 foo
)另一个模块(由其他人很久以前编写,我不想现在开始修改它)调用一个函数.foo
将有趣的东西写入 stdout
(但返回 None
),部分是通过调用其他函数.我想访问 foo
写入 stdout
的这些有趣的东西.
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
.
据我所知,subprocess
用于调用我通常从命令行调用的命令.我可以从脚本中调用 python 函数的等价物吗?
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?
如果重要的话,我使用的是 python2.7
I'm on python2.7, if it matters
推荐答案
正如@JimDeville 所评论的,您可以交换标准输出:
As @JimDeville commented, you can swap 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 流:
Python 3 version uses io.StringIO
instead due to stdout
expected to be a Unicode stream:
#!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())
这篇关于访问函数调用的打印输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!