Skip to main content
 首页 » 编程设计

python之如何获得描述子解析器(位置参数)的单行

2024年10月25日10xing901022

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

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

请您参考如下方法:

您的每个子解析器都需要一个help 参数。 add_help 用于不同目的 - 避免重复从 parent 继承的 -h 参数。

subparsers.add_parser('create_pfiles', 
                      add_help=False, 
                      description="Create pfiles", 
                      parents=[....], 
                      help='create pfiles 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 参数中:

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

要解决这个问题,您必须为每个子解析器定义用法,例如:

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