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

2024-09-26 22:52:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

$ ./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

代码

我当前使用此代码(请参见^{}了解上下文):

#!/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)

Tags: andpyimportviewaddparsergetmodel
1条回答
网友
1楼 · 发布于 2024-09-26 22:52:27

每个子parser都需要一个help参数。存在add_help是为了不同的目的—避免重复从parent继承的-h参数。你知道吗

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会影响子解析器的用法。子parser名称被添加到usage参数:

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

要解决这个问题,必须为每个子parser定义usage,例如:

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

相关问题 更多 >

    热门问题