从Python中的脚本捕获stdout

时间:2011-02-27 22:49:33

标签: python stdout sys

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

# module writer.py
import sys

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

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

# module mymodule.py
from writer import write

out = write()
print out.upper()

但这不起作用。我想出了另一种解决方案,但是它可以工作,但是请告诉我是否有更好的方法来解决问题。感谢

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

10 个答案:

答案 0 :(得分:43)

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

import subprocess

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

答案 1 :(得分:40)

以下是代码的上下文管理器版本。它产生两个值的列表;第一个是stdout,第二个是stderr。

import contextlib
@contextlib.contextmanager
def capture():
    import sys
    from cStringIO import StringIO
    oldout,olderr = sys.stdout, sys.stderr
    try:
        out=[StringIO(), StringIO()]
        sys.stdout,sys.stderr = out
        yield out
    finally:
        sys.stdout,sys.stderr = oldout, olderr
        out[0] = out[0].getvalue()
        out[1] = out[1].getvalue()

with capture() as out:
    print 'hi'

答案 2 :(得分:26)

对于未来的访问者:Python 3.4 contextlib通过redirect_stdout上下文管理器直接提供(参见Python contextlib help):

f = io.StringIO()
with redirect_stdout(f):
    help(pow)
s = f.getvalue()

答案 3 :(得分:10)

或者可能使用已存在的功能......

from IPython.utils.capture import capture_output

with capture_output() as c:
    print('some output')

c()

print c.stdout

答案 4 :(得分:9)

这是我原始代码的装饰者对应物。

writer.py保持不变:

import sys

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

mymodule.py sligthly被修改:

from writer import write as _write
from decorators import capture

@capture
def write():
    return _write()

out = write()
# out post processing...

这是装饰者:

def capture(f):
    """
    Decorator to capture standard output
    """
    def captured(*args, **kwargs):
        import sys
        from cStringIO import StringIO

        # setup the environment
        backup = sys.stdout

        try:
            sys.stdout = StringIO()     # capture output
            f(*args, **kwargs)
            out = sys.stdout.getvalue() # release output
        finally:
            sys.stdout.close()  # close the stream 
            sys.stdout = backup # restore original stdout

        return out # captured output wrapped in a string

    return captured

答案 5 :(得分:6)

从Python 3开始,您还可以使用sys.stdout.buffer.write()将已编码的字节字符串写入stdout(请参阅stdout in Python 3)。 当您这样做时,简单的StringIO方法不起作用,因为sys.stdout.encodingsys.stdout.buffer都不可用。

从Python 2.6开始,您可以使用TextIOBase API,其中包含缺少的属性:

import sys
from io import TextIOWrapper, BytesIO

# setup the environment
old_stdout = sys.stdout
sys.stdout = TextIOWrapper(BytesIO(), sys.stdout.encoding)

# do some writing (indirectly)
write("blub")

# get output
sys.stdout.seek(0)      # jump to the start
out = sys.stdout.read() # read output

# restore stdout
sys.stdout.close()
sys.stdout = old_stdout

# do stuff with the output
print(out.upper())

此解决方案适用于Python 2> = 2.6和Python 3。 请注意,我们的sys.stdout.write()只接受unicode字符串,而sys.stdout.buffer.write()只接受字节字符串。 对于旧代码可能不是这种情况,但对于构​​建为在Python 2和3上运行而无需更改的代码通常就是这种情况。

如果您需要支持直接向stdout发送字节字符串而不使用stdout.buffer的代码,则可以使用以下变体:

class StdoutBuffer(TextIOWrapper):
    def write(self, string):
        try:
            return super(StdoutBuffer, self).write(string)
        except TypeError:
            # redirect encoded byte strings directly to buffer
            return super(StdoutBuffer, self).buffer.write(string)

您不必将缓冲区的编码设置为sys.stdout.encoding,但这在使用此方法测试/比较脚本输出时会有所帮助。

答案 6 :(得分:3)

问题here(如何重定向输出,而不是tee部分的示例)使用os.dup2在操作系统级别重定向流。这很好,因为它也适用于从程序中生成的命令。

答案 7 :(得分:3)

我认为你应该看看这四个对象:

from test.test_support import captured_stdout, captured_output, \
    captured_stderr, captured_stdin

示例:

from writer import write

with captured_stdout() as stdout:
    write()
print stdout.getvalue().upper()
UPD:正如Eric在评论中所说,不应该直接使用它们,所以我复制并粘贴它。

# Code from test.test_support:
import contextlib
import sys

@contextlib.contextmanager
def captured_output(stream_name):
    """Return a context manager used by captured_stdout and captured_stdin
    that temporarily replaces the sys stream *stream_name* with a StringIO."""
    import StringIO
    orig_stdout = getattr(sys, stream_name)
    setattr(sys, stream_name, StringIO.StringIO())
    try:
        yield getattr(sys, stream_name)
    finally:
        setattr(sys, stream_name, orig_stdout)

def captured_stdout():
    """Capture the output of sys.stdout:

       with captured_stdout() as s:
           print "hello"
       self.assertEqual(s.getvalue(), "hello")
    """
    return captured_output("stdout")

def captured_stderr():
    return captured_output("stderr")

def captured_stdin():
    return captured_output("stdin")

答案 8 :(得分:3)

我喜欢contextmanager解决方案但是如果你需要使用open文件和fileno支持存储的缓冲区,你可以做这样的事情。

import six
from six.moves import StringIO


class FileWriteStore(object):
    def __init__(self, file_):
        self.__file__ = file_
        self.__buff__ = StringIO()

    def __getattribute__(self, name):
        if name in {
            "write", "writelines", "get_file_value", "__file__",
                "__buff__"}:
            return super(FileWriteStore, self).__getattribute__(name)
        return self.__file__.__getattribute__(name)

    def write(self, text):
        if isinstance(text, six.string_types):
            try:
                self.__buff__.write(text)
            except:
                pass
        self.__file__.write(text)

    def writelines(self, lines):
        try:
            self.__buff__.writelines(lines)
        except:
            pass
        self.__file__.writelines(lines)

    def get_file_value(self):
        return self.__buff__.getvalue()

使用

import sys
sys.stdout = FileWriteStore(sys.stdout)
print "test"
buffer = sys.stdout.get_file_value()
# you don't want to print the buffer while still storing
# else it will double in size every print
sys.stdout = sys.stdout.__file__
print buffer

答案 9 :(得分:2)

这是一个上下文管理器,它从@JonnyJD的answer获得启发,支持将字节写入'%'属性,但也利用sys's dunder-io referenes进行了进一步的简化。

man 3 printf

输出为:

buffer