8

重複の可能性:
Pythonのstdoutをある種の文字列バッファにリダイレクトできますか?

標準出力に何かを出力するPythonの関数があります

def foo():
    print("some text")

この関数で出力されているテキストを変数に「リダイレクト」したい。つまり、テキストが変数に格納されるように、この関数などを「ラップ」したい。

text = wrapper(foo)

変数を一時的に変更sys.stdoutしたり、変数を、などとして開くための堅牢な方法はありFileObjectますか?

4

2 に答える 2

21

python3.4+ の場合、標準ライブラリにこのためのコンテキスト マネージャがあります。

with contextlib.redirect_stdout(file_like_object):
    ...

回答のこの部分は更新されましたが、主にまだ python2.x の世界で立ち往生している人向けです

古いバージョンの Python に行き詰まっている場合、このコンテキスト マネージャーを自分で作成するのは難しくありません。sys.stdout重要なのは、必要なファイルのようなオブジェクトに更新できることです (それがprint書き込み先です)。

>>> import sys
>>> import StringIO
>>> stdout = sys.stdout  # keep a handle on the real standard output
>>> sys.stdout = StringIO.StringIO() # Choose a file-like object to write to
>>> foo() 
>>> sys.stdout = stdout
>>> foo()
bar

コンテキスト マネージャーを作成して、コンテキストに入ったときに stdout を任意の値に設定し、コンテキスト マネージャーがコンテキストに入ったときに stdout をリセットするよう__exit__にします。

contextlibコンテキストマネージャーを作成するために使用する簡単な例を次に示します。

import contextlib
import sys

@contextlib.contextmanager
def stdout_redirect(where):
    sys.stdout = where
    try:
        yield where
    finally:
        sys.stdout = sys.__stdout__

def foo():
    print 'bar'

# Examples with StringIO
import StringIO

with stdout_redirect(StringIO.StringIO()) as new_stdout:
    foo()

new_stdout.seek(0)
print "data from new_stdout:",new_stdout.read()

new_stdout1 = StringIO.StringIO()
with stdout_redirect(new_stdout1):
    foo()

new_stdout1.seek(0)
print "data from new_stdout1:",new_stdout1.read()

# Now with a file object:
with open('new_stdout') as f:
    with stdout_redirect(f):
        foo()

# Just to prove that we actually did put stdout back as we were supposed to
print "Now calling foo without context"
foo()

ノート:

python3.x では、StringIO.StringIOに移動しましたio.StringIO。また、python2.x では、cStringIO.StringIOパフォーマンスがわずかに向上する可能性があります。

于 2013-01-07T13:35:09.743 に答える
7

Python 3.x では、単に再定義できますprint

B = []

def print(str):
    global B
    B.append(str)

def A():
    print("example")

A()

>>> B
['example']

何らかの理由で組み込みのプリントバックが必要な場合は、次のようにします。

from builtins import print
于 2013-01-07T13:36:28.397 に答える