【问题标题】:Read python stdout as string将 python stdout 读取为字符串
【发布时间】:2013-01-15 19:16:17
【问题描述】:

在 Java 中,我可以使用

将标准输出作为字符串读取
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 stdout 和How 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

但这似乎不起作用。我得到了一些关于打开文件的compaints。

【问题讨论】:

    标签: java python string python-2.7 stdout


    【解决方案1】:

    如果我理解您尝试正确执行的操作,类似这样的操作将使用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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 2020-03-24
      • 2013-02-13
      • 2012-03-28
      • 1970-01-01
      相关资源
      最近更新 更多