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

Python3.11中使用redirect_stdout时如何修改默认80列的终端宽度?

在Python 3.11中修改redirect_stdout的终端宽度

Python 3.11里使用redirect_stdout捕获输出时,终端宽度默认被固定为80,这会限制argparse帮助信息的排版宽度。要自定义宽度,可通过以下方式实现:

核心思路:给输出流添加columns属性

argparse生成帮助信息时,会读取输出流的columns属性来确定换行宽度。因此,只需给StringIO对象手动添加这个属性,就能覆盖默认的80宽度。

修改后的示例代码

import io
from contextlib import redirect_stdout

def parse_help(command_list=None, width=168):
    command_list = [] if command_list is None else command_list

    s = io.StringIO()
    # 为StringIO对象指定自定义宽度
    s.columns = width
    with redirect_stdout(s):
        try:
            do_command([*command_list, '--help'])
        except SystemExit:
            pass

    help_text = s.getvalue()
    print_help(help_text)

    for subcommand in get_subcommands(help_text):
        parse_help([*command_list, subcommand], width=width)

说明

  • redirect_stdout本身并不支持width参数,你示例中的with redirect_stdout(s, width=width)写法是无效的。
  • 通过给StringIO对象添加columns属性,argparse会自动使用这个值来格式化帮助信息,实现自定义宽度的排版。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 08:27:36