Python argparse - 长参数名称的帮助文本

3

Python的'argparse'在为长命名参数显示帮助文本时,会在新行上显示:

**#script.py -h

Select one of the options given


optional arguments:
  -h, --help            show this help message and exit
  -bs , --business_service 
                        choose the service     << New line
  -so , --service_offering 
  -ci , --cmdb_ci       provide configuration item
  -desc , --description 
                        write description     << New line

以下是我使用的代码:
self.parser = argparse.ArgumentParser(
            description='Select one of the options given',
            epilog=self._get_usage(),
            formatter_class=argparse.RawTextHelpFormatter
            )


        self.parser.add_argument('-bs','--business_service',type=str,help='choose the service',metavar='')
        self.parser.add_argument('-so','--service_offering',type=str,metavar='')
        self.parser.add_argument('-ci','--mdcb_ci',type=str,help='provide configuration item',metavar='')
        self.parser.add_argument('-desc','--description',type=str,help='write description',metavar='')

我希望帮助字符串和参数在同一行上:
-bs , --business_service     choose the service     << Same line

我该如何解决这个问题?

可能需要深入研究argparse库才能实现…如果帮助文本的格式对您很重要,docopt可能是更好的选择。 - undefined
1
简化长选项名称是最简单的解决方案。 - undefined
1个回答

5

HelpFormatter 类接收一个 max_help_position 参数。默认值为 24,这也是您在帮助中看到的值。

可以通过新的格式化子类或调用参数的修改来更改它。

In [23]: parser.formatter_class = 
    lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=30)

这里我在修改formatter_class属性,但你也可以使用这个lambda语句来代替。

formatter_class=argparse.RawTextHelpFormatter

结果如下:
In [24]: parser.print_help()
usage: ipython3 [-h] [-bs] [-so] [-ci] [-desc]

Select one of the options given

optional arguments:
  -h, --help                 show this help message and exit
  -bs , --business_service   choose the service
  -so , --service_offering 
  -ci , --mdcb_ci            provide configuration item
  -desc , --description      write description

这样选择参数可以平衡显示的整体宽度和可读性。 这些参数可以进行微调,但需要一些 Python 编程知识。 我已经有一段时间没有做过这个了,所以我的建议可能不是最简单的方式,但通常是正确的方向。

使用 partial 包装器设置的另一种方法:

In [42]: from functools import partial
In [43]: newformatter=partial(argparse.HelpFormatter, max_help_position=30)
In [44]: parser.formatter_class=newformatter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接