从脚本中捕获标准输出? [英] Capture stdout from a script?

查看:51
本文介绍了从脚本中捕获标准输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个脚本在做这样的事情:

suppose there is a script doing something like this:

# module writer.py
import sys

def write():
    sys.stdout.write("foobar")

现在假设我想捕获 write 函数的输出并将其存储在一个变量中以供进一步处理.天真的解决方案是:

Now suppose I want to capture the output of the write function and store it in a variable for further processing. The naive solution was:

# module mymodule.py
from writer import write

out = write()
print out.upper()

但这行不通.我想出了另一个解决方案并且它有效,但是请告诉我是否有更好的方法来解决问题.谢谢

But this doesn't work. I come up with another solution and it works, but please, let me know if there is a better way to solve the problem. Thanks

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

推荐答案

设置 stdout 是一种合理的方法.另一种是将其作为另一个进程运行:

Setting stdout is a reasonable way to do it. Another is to run it as another process:

import subprocess

proc = subprocess.Popen(["python", "-c", "import writer; writer.write()"], stdout=subprocess.PIPE)
out = proc.communicate()[0]
print out.upper()

这篇关于从脚本中捕获标准输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆