Skip to main content
 首页 » 编程设计

python之使用 python 中的代码模块重定向标准输入的输出

2025年05月04日9mq0036

我正在尝试找出一种方法来重定向我正在编写的运行交互式控制台的脚本的输出。

我需要能够:

capture the output in a string, and then check it, or print it out.

这可行吗?我应该使用不同的 python 模块吗?

我用 subprocess 模块试过这个,但遇到了一个问题,我只能在进程结束时进行 1 次读取。那行不通,我需要从 stdout 读取多次。这是我目前所拥有的:

import code 
console = code.InteractiveConsole() 
console.push('from sim import newsteam\n') 
console.push('assembler = newsteam()\n') 
console.push('assembler.__init__()\n') 
 
line = console.push('assembler.reportr()\n') 
#I need to be able to interact with this output 
line1 = console.push('assembler.reportpc()\n') 
line2 = console.push('assembler.reportm()\n') 
 
print("this is the result: " + line + line1 + line2) 

请您参考如下方法:

您可以暂时重定向标准输出:

import code 
import sys 
from contextlib import contextmanager 
 
try: 
    from StringIO import StringIO 
except ImportError: # Python 3 
    from io import StringIO 
 
try: 
    from contextlib import redirect_stdout  
except ImportError: # Python < 3.4 
    @contextmanager 
    def redirect_stdout(new_target): 
        old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout 
        try: 
            yield new_target # run some code with the replaced stdout 
        finally: 
            sys.stdout = old_target # restore to the previous value 
 
f = StringIO() 
with redirect_stdout(f): 
    console = code.InteractiveConsole() 
    console.push('print("hello world")') 
    console.push('i = int(input("give me a number"))') 
    console.push('sq = i*i') 
    console.push('print("%d squared is %d" % (i, sq))') 
print("Got: %r" % f.getvalue()) 

例子:

$ echo 2 | python code-interactive.py  
Got: 'hello world\ngive me a number2 squared is 4\n'