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

为什么argparse的add_argument方法help参数中\n换行符不生效?

原因说明
  • argparse默认的帮助文本格式化器argparse.HelpFormatter会自动清理输入文本中的换行符、连续空白符,同时自动根据终端宽度做内容折行,所以你在help参数里手动添加的\n会被过滤,无法正常生效。
解决办法

如果需要保留自定义的换行排版,只需要在初始化ArgumentParser实例时,指定formatter_class参数为argparse.RawTextHelpFormatter即可,修改后的参考代码如下:

import argparse

my_parser = argparse.ArgumentParser(
    description='this is an example',
    formatter_class=argparse.RawTextHelpFormatter  # 新增该参数即可
)
my_parser.add_argument('-pattern', '--list', nargs='+',
                       help='choose the properties as you need:\n'
                            'including:\n'
                            'power, area, toggle, performance')

pattern = my_parser.parse_args().list
print('example exit')

修改后再次执行python help.py -h,帮助信息就会按照你设置的换行格式正常展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 11:39:03