gpt4 book ai didi

Python stdout 重定向(特殊)

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:08 32 4
gpt4 key购买 nike

我目前正在用 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com