3

Java では、stdout を文字列として読み取ることができます。

ByteArrayOutputStream stdout = new ByteArrayOutputStream();
System.setOut(new PrintStream(stdout));
String toUse = stdout.toString();

/**
 * do all my fancy stuff with string `toUse` here
 */

//Now that I am done, set it back to the console
System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));

誰かがPythonでこれを行う同等の方法を教えてもらえますか? Python: Closing a for loop by reading stdoutHow to get stdout into a string (Python)など、この質問のさまざまなフレーバーが何度も尋ねられていることを私は知っています。しかし、必要なものはそれよりも単純なので、必要なものを取得するためにサブプロセスをインポートする必要はないと感じています。私はEclipseでpydevを使用していますが、プログラムは非常に簡単です。

私はすでに試しました

from sys import stdout

def findHello():
  print "hello world"
  myString = stdout

  y = 9 if "ell" in myString else 13

しかし、それは機能していないようです。ファイルを開くことについていくつかの苦情があります。

4

1 に答える 1

3

あなたが適切にやろうとしていることを私が理解していれば、このようなものはStringIOオブジェクトを使用して、あなたが書いたものをキャプチャしstdout、値を取得できるようにします:

from StringIO import StringIO
import sys

stringio = StringIO()
previous_stdout = sys.stdout
sys.stdout = stringio

# do stuff

sys.stdout = previous_stdout

myString = stringio.getvalue()

もちろん、これは実際にオリジナルに行く出力を抑制しますstdout。出力をコンソールに出力したいが、それでも値を取得したい場合は、次のようなものを使用できます。

class TeeOut(object):
    def __init__(self, *writers):
        self.writers = writers

    def write(self, s):
        for writer in self.writers:
            writer.write(s)

そして、次のように使用します。

from StringIO import StringIO
import sys

stringio = StringIO()
previous_stdout = sys.stdout
sys.stdout = TeeOut(stringio, previous_stdout)

# do stuff

sys.stdout = previous_stdout

myString = stringio.getvalue()
于 2013-01-31T17:19:09.777 に答える