如何获得描述subparser的单行(位置参数)?

时间:2014-11-21 06:24:42

标签: python argparse

我目前有一个带有子分析器的解析器,它提供了以下帮助:

$ ./hwrt --help
usage: hwrt [-h] [--version]
            {create_pfiles,create_model,view,download,check} ...

hwrt, the handwriting recognition toolkit, is a set of executable scripts and
Python modules that are useful for handwriting recognition. Current scripts
include: analyze_data.py, backup.py, download.py, view.py For train.py,
test.py and get_top_n_error.py you will need an internal toolkit for training
of neural networks.

positional arguments:
  {create_pfiles,create_model,view,download,check}

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

我想得到什么

看看"位置参数"。它们都应该有描述文字。

./hwrt --help
usage: hwrt [-h] [--version]
            {create_pfiles,create_model,view,download,check} ...

hwrt, the handwriting recognition toolkit, is a set of executable scripts and
Python modules that are useful for handwriting recognition. Current scripts
include: analyze_data.py, backup.py, download.py, view.py For train.py,
test.py and get_top_n_error.py you will need an internal toolkit for training
of neural networks.

positional arguments:
  create_pfiles    A tool to create compressed feature files from preprocessed
                   files.
  create_model     Create a model file.
  view             Display raw preprocessed recordings.
  download         Download the raw data to start analyzation / traning.
  check            Self-check of the HWRT toolkit.

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

代码

我目前使用此代码(有关上下文,请参阅bin/hwrt):

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""hwrt, the handwriting recognition toolkit, is a set of executable scripts
   and Python modules that are useful for handwriting recognition.

   Current scripts include: analyze_data.py, backup.py, download.py, view.py

   For train.py, test.py and get_top_n_error.py you will need an internal
   toolkit for training of neural networks.
"""


import argparse

import logging
import sys
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
                    level=logging.DEBUG,
                    stream=sys.stdout)

# hwrt modules
# Every HWR tool that should be available through
#   hwrt TOOL
# has to be added to ``get_parser()`` and to ``main``.
import hwrt
from hwrt import create_pfiles
from hwrt import create_model
from hwrt import selfcheck
from hwrt import view
from hwrt import download


def get_parser():
    """Return the parser object for this script."""
    parser = argparse.ArgumentParser(description=__doc__,
                                     prog='hwrt')
    subparsers = parser.add_subparsers(dest='cmd')
    subparsers.add_parser('create_pfiles',
                          add_help=False,
                          description="Create pfiles",
                          parents=[create_pfiles.get_parser()])
    subparsers.add_parser('create_model',
                          add_help=False,
                          parents=[create_model.get_parser()])
    subparsers.add_parser('view',
                          add_help=False,
                          parents=[view.get_parser()])
    subparsers.add_parser('download',
                          add_help=False,
                          parents=[download.get_parser()])
    subparsers.add_parser('check',
                          add_help=False)
    parser.add_argument('--version',
                        action='version',
                        version=('hwrt %s' % str(hwrt.__version__)))
    return parser


def main(args):
    if args.cmd == 'check':
        selfcheck.main()
    elif args.cmd == 'view':
        view.main(args.list, args.model, args.server, args.id, args.show_raw,
                  args.mysql)
    elif args.cmd == 'download':
        download.main()

if __name__ == '__main__':
    args = get_parser().parse_args()
    main(args)

1 个答案:

答案 0 :(得分:2)

每个子分析符都需要help个参数。 add_help用于不同目的 - 避免重复-h继承的parent参数。

subparsers.add_parser('create_pfiles',
                      add_help=False,
                      description="Create pfiles",
                      parents=[....],
                      help='create pfiles help')

help更改为

positional arguments:
  {create_pfiles,create_model,view,download,check}
    create_pfiles       create pfiles help

您可以使用.description属性访问父解析器的描述。


可以使用metavar更改{}中的选项列表。但它会影响使用和帮助中的列表。要覆盖使用情况,您必须为其提供自定义使用行。例如:

usage = "%(prog)s [-h] [--version] {create_pfiles,create_model,...} ..."
parser = argparse.ArgumentParser(description=__doc__,
                                 prog='hwrt',
                                 usage=usage)
subparsers = parser.add_subparsers(dest='cmd', help='subparsers choices',
    metavar='')

产生

usage: hwrt [-h] [--version] {create_pfiles,create_model,...} ...

positional arguments:
                 subparsers choices
    create_pfiles
                 create pfiles help
    create_model
                 p1 description
    ....

不幸的是,为主解析器定义usage会影响subparsers出现的用法。 subparser名称将添加到usage参数:

usage: hwrt [-h] [--version] {create_pfiles,create_model,...} ... create_pfiles

要解决这个问题,你必须为每个子分析器定义usage,例如:

subparsers.add_parser('create_pfiles',
                      ...,
                      help='create pfiles help',
                      usage='create_pfiles usage')