You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何获取最后一次控制台输出(兼容多控制台环境)

实现方案

不依赖特定控制台特性、跨环境通用的实现方式是直接包装标准输出流,拦截所有写入sys.stdout的内容,在保证正常输出功能不受影响的前提下缓存最近一次写入的片段。

完整实现代码

import sys

class _OutputCatcher:
    def __init__(self, raw_stdout):
        self._raw_stdout = raw_stdout
        self.last_output = ""

    def write(self, content):
        # 转发内容到原始输出流,不干扰正常打印
        self._raw_stdout.write(content)
        # 覆盖缓存最近一次写入的内容
        self.last_output = content

    def flush(self):
        self._raw_stdout.flush()

# 替换系统标准输出为自定义包装器
_raw_stdout = sys.stdout
sys.stdout = _OutputCatcher(_raw_stdout)

def get_last_output():
    return sys.stdout.last_output

效果验证

运行测试逻辑,输出完全符合预期:

print("Hello World")
last_output = get_last_output()
print() # 分隔内容避免混淆

print(repr(last_output))
# 打印结果: '\n'


print("Hello World", end="")
last_output = get_last_output()
print() # 分隔内容避免混淆

print(repr(last_output))
# 打印结果: 'Hello World'

说明

  • 该方案不依赖任何终端专有API,无论是输出到控制台、重定向到文件、走管道传输都能正常捕获内容,无环境限制
  • 对原有业务代码无侵入,不需要修改已有的print调用逻辑
  • 如果需要停止捕获,执行sys.stdout = _raw_stdout即可还原默认输出行为

内容的提问来源于stack exchange,提问作者Baelfire18

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 14:18:12