Python 标准输出重定向(特殊)

Python stdout redirection (special)

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

为了这样做,我需要有一个选项来获取第一个命令要打印的内容(请注意,该命令可能不是系统命令,而是一个 python 文件,其中包含以下行

print 'some information'

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

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

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'