为什么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
相关产品推荐
相关产品推荐

