【问题标题】:How to reattach sys.stdout to console window in python?如何将 sys.stdout 重新附加到 python 中的控制台窗口?
【发布时间】:2015-09-04 16:26:54
【问题描述】:

我的 python 3 涂鸦是这样的:

import io, sys
sys.stdout = io.StringIO()
# no more responses to python terminal funnily enough

我的问题是如何重新连接,所以当我传入1+1 时,它会以2 返回到控制台?

这是在 windows 7 64 位上运行的 32 位 python 上的 python 解释器中。

【问题讨论】:

  • 您在哪里/如何接受输入?
  • 我可以@AnandSKumar,但我正在试验标准输出的工作方式,以及是否要创建一个自定义的类文件对象以可能将标准输出重定向到该对象。
  • @user1561108,您真的要存储所有输出吗?
  • @PadraicCunningham 只是一个学习练习。我想要做的是通过将 sys.stdout 设置为一个类似文件的虚拟对象来抑制输出。到目前为止,我的类通过传递实现了刷新和写入,但是当我将 sys.stdout 设置为它的一个实例时,我的应用程序在运行时抱怨它是对 NoneType 对象的调用刷新。

标签: python io stdout stringio redirectstandardoutput


【解决方案1】:

您正在寻找sys.__stdout__:

它还可用于将实际文件恢复为已知的工作文件对象,以防它们被损坏的对象覆盖。但是,执行此操作的首选方法是在替换之前显式保存先前的流,然后恢复保存的对象。

【讨论】:

    【解决方案2】:

    我不确定你是如何接受输入的,但这会做你想做的:

    import io, sys
    
    f = io.StringIO()
    sys.stdout = f
    
    while True:
        inp = input()
        if inp == "1+1":
            print(inp)
            break
    sys.stdout = sys.__stdout__
    print(eval(f.getvalue()))
    

    或者获取inp的最后一个值:

    import io, sys
    
    f = io.StringIO()
    sys.stdout = io.StringIO()
    
    while True:
        inp = input()
        if inp == "1+1":
            print(inp)
            break
    sys.stdout = sys.__stdout__
    print(eval(inp))
    

    或者遍历标准输入:

    import io, sys
    
    sys.stdout = io.StringIO()
    for line in sys.stdin:
        if line.strip() == "1+1":
            print(line)
            break
    sys.stdout = sys.__stdout__
    print(eval(line))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多