首页 > 解决方案 > Python argparse - 子解析器的打印帮助?

问题描述

我有一系列子解析器,每个子解析器都有一个帮助字符串,总结了它的作用。当我请求整体帮助时,argparse 将列出子解析器及​​其帮助字符串。

当我为特定的子解析器寻求帮助时,它不再打印出该子解析器的帮助字符串。

我的问题:当 argparse 打印出特定子解析器的帮助时,是否可以获得子解析器的帮助字符串(除了该子解析器的详细选项)

这是我的最低工作示例。给定以下代码:

import argparse

parser = argparse.ArgumentParser()

subparsers = parser.add_subparsers(dest='command', help='sub-command help')

parser_ag = subparsers.add_parser(  'mySubcommand',
                                    help='Subcommand help')
parser_ag.add_argument( '-g',  action='store_true',
                        help='optional parameter for subcommand')

那么该行将parser.parse_args(['-h'])产生:

usage: MWE_SubparserOptionalArgs.py [-h] {mySubcommand} ...

positional arguments:
  {mySubcommand}  sub-command help
    mySubcommand  Subcommand help  <============================== Note the 'Subcommand help' string here!!!

optional arguments:
  -h, --help      show this help message and exit

该生产线parser.parse_args('mySubcommand -h'.split())将产生:

usage: MWE_SubparserOptionalArgs.py mySubcommand [-h] [-g]
 <================================  It would be nice for the 'Subcommand help' string to appear here!
optional arguments:
  -h, --help  show this help message and exit
  -g          optional parameter for subcommand

我的问题是:是否可以让 argparse 打印出“子命令帮助”字符串以及 mySubcommand 子解析器的帮助信息?

在此先感谢 - 任何帮助将不胜感激!

标签: pythonargparse

解决方案


推荐阅读