【问题标题】:Format argparse help for positional arguments位置参数的格式 argparse 帮助
【发布时间】:2017-03-29 00:34:01
【问题描述】:

默认argparse帮助输出很难看:

usage: gl.EXE [-h] [--version]
              {track,untrack,status,diff,commit,branch,tag,checkout,merge,resolve,fuse,remote,publish,switch,init,history}
              ...

Gitless - a version control system built on top of Git - http://gitless.com

optional arguments:
  -h, --help            show this help message and exit
  --version             show program's version number and exit

subcommands:
  {track,untrack,status,diff,commit,branch,tag,checkout,merge,resolve,fuse,remote,publish,switch,init,history}
    track               start tracking changes to files
    untrack             stop tracking changes to files
    status              show status of the repo
...

如何将输出格式化为与下面的示例完全相同。保留命令顺序

Gitless - a version control system built on top of Git - http://gitless.com

commands:

  track               start tracking changes to files
  untrack             stop tracking changes to files
  status              show status of the repo
...

【问题讨论】:

    标签: argparse user-experience


    【解决方案1】:

    子类化 argparse.RawDescriptionHelpFormatter 工作量太大,所以我使用这个 hack 来提取命令列表并构建我自己的消息。

    def print_help(parser):
      """print help for humans"""
      print(parser.description)
      print('\ncommands:\n')
    
      # https://stackoverflow.com/questions/20094215/argparse-subparser-monolithic-help-output
      # retrieve subparsers from parser
      subparsers_actions = [
          action for action in parser._actions 
          if isinstance(action, argparse._SubParsersAction)]
      # there will probably only be one subparser_action,
      # but better save than sorry
      for subparsers_action in subparsers_actions:
          # get all subparsers and print help
          for choice in subparsers_action._choices_actions:
              print('    {:<19} {}'.format(choice.dest, choice.help))
    

    【讨论】:

    • 是的,因为有这么大的变化,自己编写通常更容易。看起来你很好地利用了前面的讨论。对于不太大的更改,编写自定义 parser.format_help 是另一种选择。
    • @hpaulj,前面的讨论帮助很大,但仍然需要花费大量时间来调试 argparse 代码才能得到这个 sn-p。自定义解析器类非常庞大,如果可能,我更喜欢保持 CLI 代码紧凑。
    猜你喜欢
    • 2011-07-24
    • 2021-09-24
    • 2010-10-13
    • 2011-05-27
    • 1970-01-01
    • 2011-05-21
    • 2016-06-30
    • 1970-01-01
    • 2020-10-12
    相关资源
    最近更新 更多