【发布时间】:2022-01-04 21:05:51
【问题描述】:
我有一个像 'git' 这样的多级命令行程序。
my_cli service action --options
我想逐级显示帮助消息,并且我不希望用户显式键入“-h”或“--help”。
例如,
$ my_cli <== display help of all services
$ my_cli service1 <== display help for service1 only
$ my_cli service1 action1 <== display help for service1/action1 only
代码如下所示。
import argparse
argument_parser = argparse.ArgumentParser(description="my_cli")
root_parsers = argument_parser.add_subparsers(title="service", dest="service")
service1_parsers = root_parsers.add_parser("service1", help="service1").add_subparsers(title="action", dest="action")
service2_parsers = root_parsers.add_parser("service2", help="service2").add_subparsers(title="action", dest="action")
service1_action1_parser = service1_parsers.add_parser("action1", help="action1")
service1_action1_parser.add_argument("-a", "--address", required=True, help="address or hostname of the server")
...
args = argument_parser.parse_args()
if (args.service is None):
argument_parser.print_help()
exit(1)
elif (args.action is None):
if (args.service == "service1"):
service1_parsers.print_help() <== This doesn't work.
exit(1)
...
else:
if (args.service == "service1") AND (args.action == "action1"):
service1_action1_parser.print_help() <== This doesn't work.
exit(1)
...
【问题讨论】:
标签: python-3.x argparse