【问题标题】:Python stdout redirection (special)Python 标准输出重定向(特殊)
【发布时间】:2016-12-10 09:41:23
【问题描述】:

我目前正在用 python 构建一个 shell。 shell可以执行python文件,但我还需要添加使用PIPEs的选项(例如'|'表示第一个命令的输出将是第二个命令的输入)。

为了做到这一点,我需要选择第一个命令要打印的内容(请注意,该命令可能不是系统命令,而是具有行

的 python 文件
print 'some information'

我需要将它传递给 shell 中的一个变量。 有人可以帮忙吗?

【问题讨论】:

    标签: python python-2.7 shell stdout


    【解决方案1】:

    您可以将sys.stdout 重定向到内存中的BytesIOStringIO 类文件对象:

    import sys
    from io import BytesIO
    
    buf = BytesIO()
    sys.stdout = buf
    
    # Capture some output to the buffer
    print 'some information'
    print 'more information'
    
    # Restore original stdout
    sys.stdout = sys.__stdout__
    
    # Display buffer contents
    print 'buffer contains:', repr(buf.getvalue())
    buf.close()
    

    输出

    buffer contains: 'some information\nmore information\n'
    

    【讨论】:

    • 我试过这个。我没有使用“打印”,而是尝试了 os.system('dir')。它仍然打印到屏幕上,尽管它在 buf 中输入了 0。所以它接受了这个响应,但并没有阻止里面的打印...... :(
    • @OphirBack 那是因为os.system 在继承shell 的原始stdinstdoutstderr 句柄的子shell 中运行,所以它不受我的代码执行的重定向的影响。但是你不应该使用os.system,除了非常简单的东西。看看subprocess 模块,它可以让您控制命令的输入和输出。
    • @OphirBack 另外,请认真考虑使用 Python 3。在 Python 2 中开发新东西没有多大意义,因为 2020 年后将不再支持它。
    • 我不确定子流程的事情所以非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2014-01-20
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多