argparse 子解析器整体帮助输出 [英] argparse subparser monolithic help output

查看:25
本文介绍了argparse 子解析器整体帮助输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 argparse 在顶层只有 3 个标志 (store_true),其他一切都通过子解析器处理.当我运行 myprog.py --help 时,输出显示所有子命令的列表,如正常的 {sub1, sub2, sub3, sub4, ...}.所以,默认的效果很好......

My argparse has only 3 flags (store_true) on the top level, everything else is handled through subparsers. When I run myprog.py --help, the output shows a list of all subcommands like normal, {sub1, sub2, sub3, sub4, ...}. So, the default is working great...

我通常不记得我需要的确切子命令名称及其所有选项.所以我最终做了 2 个帮助查找:

I usually can't remember the exact subcommand name I need, and all of its options. So I end up doing 2 help lookups:

myprog.py --help
myprog.py sub1 --help

我经常这样做,我决定把它塞进一个步骤.我宁愿让我的顶级帮助输出一个巨大的摘要,然后我手动滚动列表.我发现它要快得多(至少对我而言).

I do this so often, I decided to cram this into one step. I would rather have my toplevel help output a huge summary, and then I scroll through the list manually. I find it is much faster (for me at least).

我使用的是 RawDescriptionHelpFormatter,并手动输入长帮助输出.但是现在我有很多子命令,管理起来很痛苦.

I was using a RawDescriptionHelpFormatter, and typing the long help output by hand. But now I have lots of subcommands, and its becoming a pain to manage.

有没有办法只调用一个程序就获得详细的帮助输出?

Is there a way to get a verbose help output with just one program call?

如果没有,我如何迭代我的 argparse 实例的子解析器,然后从每个子解析器中单独检索帮助输出(然后我将把它们粘在一起)?

If not, how can I iterate the subparsers of my argparse instance, and then retrieve the help output individually from each one (which I will then later glue together)?

这是我的 argparse 设置的快速概述.我清理/剥离了一些代码,所以如果没有一点帮助,它可能无法运行.

Here is a quick outline of my argparse setup. I cleaned/stripped the code a fair bit, so this may not run without a bit of help.

parser = argparse.ArgumentParser(
        prog='myprog.py',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description=textwrap.dedent(""" You can manually type Help here """) )

parser.add_argument('--debuglog', action='store_true', help='Verbose logging for debug purposes.')
parser.add_argument('--ipyonexit', action='store_true', help='Drop into an embeded Ipython session instead of exiting command.')

subparser = parser.add_subparsers()

### --- Subparser B
parser_b = subparser.add_parser('pdfreport', description="Used to output reports in PDF format.")
parser_b.add_argument('type', type=str, choices=['flatlist', 'nested', 'custom'],
                        help="The type of PDF report to generate.")
parser_b.add_argument('--of', type=str, default='',
                        help="Override the path/name of the output file.")
parser_b.add_argument('--pagesize', type=str, choices=['letter', '3x5', '5x7'], default='letter',
                        help="Override page size in output PDF.")
parser_b.set_defaults(func=cmd_pdf_report)

### ---- Subparser C
parser_c = subparser.add_parser('dbtables', description="Used to perform direct DB import/export using XLS files.")
parser_c.add_argument('action', type=str, choices=['push', 'pull', 'append', 'update'],
                        help="The action to perform on the Database Tables.")
parser_c.add_argument('tablename', nargs="+",
                        help="The name(s) of the DB-Table to operate on.")
parser_c.set_defaults(func=cmd_db_tables)

args = parser.parse_args()
args.func(args)

推荐答案

这有点棘手,因为 argparse 不直接公开已定义的子解析器列表.但是可以做到:

This is a bit tricky, as argparse does not expose a list of defined sub-parsers directly. But it can be done:

import argparse

# create the top-level parser
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('--foo', action='store_true', help='foo help')
subparsers = parser.add_subparsers(help='sub-command help')

# create the parser for the "a" command
parser_a = subparsers.add_parser('a', help='a help')
parser_a.add_argument('bar', type=int, help='bar help')

# create the parser for the "b" command
parser_b = subparsers.add_parser('b', help='b help')
parser_b.add_argument('--baz', choices='XYZ', help='baz help')
# print main help
print(parser.format_help())

# 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 safe than sorry
for subparsers_action in subparsers_actions:
    # get all subparsers and print help
    for choice, subparser in subparsers_action.choices.items():
        print("Subparser '{}'".format(choice))
        print(subparser.format_help())

此示例适用于 python 2.7 和 python 3.示例解析器来自 关于 argparse 子命令的 Python 2.7 文档.

This example should work for python 2.7 and python 3. The example parser is from Python 2.7 documentation on argparse sub-commands.

剩下要做的就是为完整的帮助添加一个新参数,或者替换内置的 -h/--help.

The only thing left to do is adding a new argument for the complete help, or replacing the built in -h/--help.

这篇关于argparse 子解析器整体帮助输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆