Python stdout 重定向(特殊)

标签 python python-2.7 shell stdout

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

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

print 'some information'

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

最佳答案

您可以将 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'

关于Python stdout 重定向(特殊),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41074125/

相关文章:

Python Json 解析

python - 为类构造函数提供默认值的大多数 Python 方式

regex - 从 URL 中删除文件名

shell - 带有 argparse 的 fish 函数的命名参数

bash - 临时更改 bash 中的当前工作目录以运行命令

python - PyCharm 和 Python 日志记录的正确工作流程

Mac OS X 终端中的 Python unicode

python - Django 1.11.17 TypeError : 'context must be a dict rather than Context' , 除了它是一个字典

python - 如何将 dict(zip(range(n), range(n))) 翻译成 Python 3?

python - 逐行打印 SSH 输出,而不是一次打印所有内容