【问题标题】:suppressing print as stdout python将打印抑制为标准输出 python
【发布时间】:2012-04-14 12:45:36
【问题描述】:

好吧..所以可能一个例子是解释这个问题的好方法

所以我有这样的事情:

if __name__=="__main__"
    result = foobar()
    sys.stdout.write(str(result))
    sys.stdout.flush()
    sys.exit(0)

现在这个脚本是从一个 ruby​​ 脚本调用的.. 基本上它在那里解析结果。 但是 foobar() 有很多打印语句.. 并且 stdout 也会刷新所有这些打印。 有没有办法(除了记录数学)我可以在这里修改一些东西,它会自动抑制这些打印并刷新这个结果? 谢谢

【问题讨论】:

    标签: python


    【解决方案1】:

    您想暂时隐藏(或隐藏)标准输出。像这样的:

    actualstdout = sys.stdout
    sys.stdout = StringIO()
    result = foobar()
    sys.stdout = actualstdout
    sys.stdout.write(str(result))
    sys.stdout.flush()
    sys.exit(0)
    

    您需要为 sys.stdout 分配类似文件的内容,以便其他方法可以有效地使用它。 StringIO 是一个很好的候选者,因为它不需要磁盘访问(它只会在内存中收集)然后被丢弃。

    【讨论】:

    • 太棒了..正是我需要的:)
    • sys.stdout = open(os.devnull,'w')代替StringIO()怎么样?
    • @ovgolovin - 如果没有期望您可能需要输出,这绝对是合理的。使用 StringIO,如果需要,您可以在重置 stdout 的原始值之前检索它。
    • 如果您使用的是 Windows,请注意 Windows 错误 - Cannot redirect output when I run Python script on Windows using just script's name
    • 对于任何像我一样出现的人......不要在 ipython 控制台中尝试这个:)
    【解决方案2】:

    对于 Python 3.4 及更高版本,您可以像这样使用redirect_stdout contextmanager:

    with redirect_stdout(open(os.devnull, "w")):
        print("This text goes nowhere")
    print("This text gets printed normally")
    

    【讨论】:

      【解决方案3】:
      import sys
      
      class output:
          def __init__(self):
              self.content = []
          def write(self, string):
              self.content.append(string)
      
      
      if __name__=="__main__":
      
          out = output()                   
          sys.stdout = out                   #redirecting the output to a variable content
      
          result = foobar()
          sys.stdout.write(str(result))
          sys.stdout.flush() 
      
          sys.stdout = sys.__stdout__        #redirecting the output back to std output   
          print "o/p of foo :",out.content
      
          sys.exit(0)
      

      【讨论】:

        【解决方案4】:

        This link shows how to redirect stdout in python。将其重定向到内部管道,然后读取您的管道并过滤掉不需要的行。这将使您只保留您感兴趣的行。

        【讨论】: