gpt4 book ai didi

python - 将 python 函数的输出从 STDOUT 重定向到 Python 中的变量

转载 作者:行者123 更新时间:2023-11-28 20:50:04 29 4
gpt4 key购买 nike

这就是我想要实现的目标


def fun():
runner = InteractiveConsole()
while(True):
code = raw_input()
code.rstrip('\n')
# I want to achieve the following
# By default the output and error of the 'code' is sent to STDOUT and STDERR
# I want to obtain the output in two variables out and err
out,err = runner.push(code)

到目前为止,我看过的所有解决方案都是使用任一管道发出单独的脚本执行命令(这在我的情况下是不可能的)。还有其他方法可以实现吗?

最佳答案

import StringIO, sys
from contextlib import contextmanager

@contextmanager
def redirected(out=sys.stdout, err=sys.stderr):
saved = sys.stdout, sys.stderr
sys.stdout, sys.stderr = out, err
try:
yield
finally:
sys.stdout, sys.stderr = saved


def fun():
runner = InteractiveConsole()
while True:
out = StringIO.StringIO()
err = StringIO.StringIO()
with redirected(out=out, err=err):
out.flush()
err.flush()
code = raw_input()
code.rstrip('\n')
# I want to achieve the following
# By default the output and error of the 'code' is sent to STDOUT and STDERR
# I want to obtain the output in two variables out and err
runner.push(code)
output = out.getvalue()
print output

在较新版本的 python 中,这个 contezt 管理器是内置的:

with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
...

关于python - 将 python 函数的输出从 STDOUT 重定向到 Python 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13250050/

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