首页  >  文章  >  后端开发  >  如何在 Python 中捕获脚本 stdout 输出?

如何在 Python 中捕获脚本 stdout 输出?

Barbara Streisand
Barbara Streisand原创
2024-10-17 15:02:03939浏览

How to Capture Script stdout Output in Python?

从 Python 脚本中捕获 stdout 输出

使用外部脚本时,通常需要捕获其 stdout 输出以进行进一步处理。一种常见的方法是使用 write() 函数打印输出,然后将其存储在变量中。然而,这种方法并不总是有效,如以下脚本所示:

<code class="python"># module writer.py
import sys

def write():
    sys.stdout.write("foobar")</code>

为了捕获 write() 函数的输出,提出了涉及 cStringIO 模块的解决方案:

<code class="python">import sys
from cStringIO import StringIO

# setup the environment
backup = sys.stdout

# ####
sys.stdout = StringIO()     # capture output
write()
out = sys.stdout.getvalue() # release output
# ####

sys.stdout.close()  # close the stream 
sys.stdout = backup # restore original stdout

print out.upper()   # post processing</code>

但是,还有更高效、Pythonic 的方法来实现此目标:

使用 contextlib.redirect_stdout (Python 3.4 )

此方法利用 contextlib .redirect_stdout 上下文管理器临时将 stdout 输出重定向到 StringIO 对象:

<code class="python">from contextlib import redirect_stdout
import io

f = io.StringIO()
with redirect_stdout(f):
    help(pow)
s = f.getvalue()</code>

直接使用 io.StringIO

另一种方法是直接创建 StringIO 对象并手动将 stdout 输出路由到它:

<code class="python">import io

output = io.StringIO()
sys.stdout = output
write()
sys.stdout.seek(0)
captured_output = output.read()</code>

通过实现这些方法,开发人员可以有效地捕获和处理脚本输出,而无需诉诸复杂的解决方法。

以上是如何在 Python 中捕获脚本 stdout 输出?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn