Python3 argparse多层子命令

代码如下:

#!/usr/bin/env python3

import argparse

def cmd1Get(args):
	print("cmd1 get")
	print(args)

def cmd2Set(args):
	print("cmd2 set")
	print(args)

parser = argparse.ArgumentParser()

subparser = parser.add_subparsers(dest="subcmd", title="subcmd")

cmd1 = subparser.add_parser("cmd1", help="cmd1 help")
cmd2 = subparser.add_parser("cmd2", help="cmd2 help")

sub_subparser = cmd1.add_subparsers(dest="subsubcmd", title="subsubcmd")
get = sub_subparser.add_parser("get", help="op get")
get.set_defaults(func=cmd1Get)

sub_subparser = cmd2.add_subparsers(dest="subsubcmd", title="subsubcmd")
set = sub_subparser.add_parser("set", help="op set")
set.set_defaults(func=cmd2Set)

get.add_argument("--id", help="ID", type=str, required=True)
set.add_argument("--id", help="ID", type=str, required=True)


args = parser.parse_args()

if not args.subcmd:
	parser.print_help()
elif not args.subsubcmd:
	subparser.choices[args.subcmd].print_help() # 输出子命令的帮助
else:
	args.func(args)

可用子命令:

$ ./cmd.py -h
usage: cmd.py [-h] {cmd1,cmd2} ...

optional arguments:
  -h, --help   show this help message and exit

subcmd:
  {cmd1,cmd2}
    cmd1       cmd1 help
    cmd2       cmd2 help

子命令的可用子命令

$ ./cmd.py cmd1 -h
usage: cmd.py cmd1 [-h] {get} ...

optional arguments:
  -h, --help  show this help message and exit

subsubcmd:
  {get}
    get       op get

子命令的子命令的帮助

$ ./cmd.py cmd1 get -h
usage: cmd.py cmd1 get [-h] --id ID

optional arguments:
  -h, --help  show this help message and exit
  --id ID     ID

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注