我目前正在用 python 构建一个 shell。 shell 可以执行 python 文件,但我还需要添加使用 PIPE 的选项(例如“|”表示第一个命令的输出将是第二个命令的输入)。
为了做到这一点,我需要有一个选项来获取第一个命令要打印的内容(请注意,该命令可能不是系统命令,而是一个包含以下行的 python 文件:
print 'some information'
我需要将它传递给 shell 中的变量。 有人可以帮忙吗?
最佳答案
您可以将 sys.stdout
重定向到内存中 BytesIO
或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'
关于Python stdout 重定向(特殊),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41074125/