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

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

Patricia Arquette
Patricia Arquette原创
2024-10-17 14:57:02919浏览

How to Capture Standard Output in Python Scripts?

捕获脚本标准输出

在脚本执行特定任务(例如将数据写入其标准输出)的场景中,捕获该输出对于进一步加工至关重要。一种常见的方法是尝试将输出存储在变量中,如下例所示:

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

def write():
    sys.stdout.write("foobar")</code>
<code class="python"># mymodule.py
from writer import write

out = write()
print(out.upper())</code>

但是,此方法无法捕获脚本的输出。另一种解决方案使用 StringIO 对象和环境设置,成功捕获输出:

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

Python 3.4 解决方案

对于 Python 版本 3.4 及更高版本,更多使用 contextlib.redirect_stdout 上下文管理器可以使用简单的方法:

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

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

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

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