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

Python实现stdout全局缩进及columnize输出缩进方案咨询

Python 实现 stdout 自动缩进或给 columnize 输出加缩进

一、全局自动缩进所有 stdout 输出

可以通过包装 sys.stdout 实现全局自动缩进,所有打印到 stdout 的内容都会被自动加上缩进,无需手动修改每一处输出代码:

import sys
import cmd

class IndentedStdout:
    def __init__(self, indent='\t'):
        self.indent = indent
        self.stdout = sys.stdout
        self._need_indent = True

    def write(self, text):
        lines = text.split('\n')
        for line in lines[:-1]:
            if self._need_indent and line.strip():
                self.stdout.write(self.indent + line + '\n')
            else:
                self.stdout.write(line + '\n')
            self._need_indent = True
        if lines[-1]:
            if self._need_indent and lines[-1].strip():
                self.stdout.write(self.indent + lines[-1])
            else:
                self.stdout.write(lines[-1])
            self._need_indent = lines[-1].endswith('\n')
        else:
            self._need_indent = True

    def flush(self):
        self.stdout.flush()

# 启用全局缩进(这里用4空格,可换成'\t')
sys.stdout = IndentedStdout(indent='    ')

# 测试 columnize 输出
cli = cmd.Cmd()
cli.columnize(['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape'], displaywidth=50)

这个包装类会自动识别非空行,仅给有内容的行添加缩进,不会给空行加多余缩进,同时处理连续换行的边界情况。

二、单独给 columnize 输出加缩进

如果不想全局修改输出行为,只想给 columnize 的输出加缩进,可以通过捕获它的输出再处理:

import cmd
import io

def indented_columnize(cli, items, displaywidth, indent='\t'):
    # 临时替换 cmd 的 stdout 为内存流,捕获输出
    original_stdout = cli.stdout
    try:
        cli.stdout = io.StringIO()
        cli.columnize(items, displaywidth=displaywidth)
        output_content = cli.stdout.getvalue()
    finally:
        cli.stdout = original_stdout  # 恢复原 stdout
    
    # 给每一行(非空行)添加缩进
    indented_lines = []
    for line in output_content.split('\n'):
        if line.strip():
            indented_lines.append(indent + line)
        else:
            indented_lines.append(line)
    print('\n'.join(indented_lines))

# 使用示例
cli = cmd.Cmd()
indented_columnize(
    cli,
    ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape'],
    displaywidth=50,
    indent='    '
)

原理是利用 io.StringIO 临时接管 cmd 实例的输出流,拿到 columnize 的输出文本后,逐行处理添加缩进,最后再打印。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:35:24