将子子命令添加到命令

时间:2019-06-04 00:19:13

标签: python argparse

我有一个python脚本,可从CLI进行输入,解析并运行适当的功能:

command subcommand subsubcommand1 --arg1 <value1>

当用户不提供子命令时,我希望脚本返回错误,说必须提供至少一个受支持的子命令,而是返回:

Namespace object has no attribute func

这是代码:

parser = argparse.ArgumentParser(description='The highlevel command')
parser.add_argument("-v", help="some help text", action='store_true', default=False)
subparsers = parser.add_subparsers(dest='action')
subparsers.required = True

subcommand_parser = subparsers.add_parser('subcommand', help='some help text for the subcommand')
subsub_subparser = subcommand_parser.add_subparsers()
subsubparser1 = subsub_subparser.add_parser('subsubcommand1', help='some help text for the subsubcommand1')
subsubparser1.set_defaults(action='subsubcommand_action', func=mylib.subsub1)
subsubparser1.add_argument('--arg1', required=True, help='arg1')
subsubparser1.add_argument('--arg2', required=False, default='hello', help='arg2')

如何解决当前错误并显示新错误?

1 个答案:

答案 0 :(得分:0)

纠正我的评论中提到的遗漏:

import argparse

parser = argparse.ArgumentParser(description='The highlevel command')
parser.add_argument("-v", help="some help text", action='store_true', default=False)
subparsers = parser.add_subparsers(dest='action')
subparsers.required = True

subcommand_parser = subparsers.add_parser('subcommand', help='some help text for the subcommand')
subsub_subparser = subcommand_parser.add_subparsers(dest='subaction')   # EDIT
subsub_subparser.required = True             # EDIT
subsubparser1 = subsub_subparser.add_parser('subsubcommand1', help='some help text for the subsubcommand1')
subsubparser1.set_defaults(func="mylib.subsub1")          # EDIT
subsubparser1.add_argument('--arg1', required=True, help='arg1')
subsubparser1.add_argument('--arg2', required=False, default='hello', help='arg2')

subsubparser2 = subsub_subparser.add_parser('subsubcommand2')  # EDIT

args = parser.parse_args()     
print(args)               # EDIT
if hasattr(args, 'func'):
    print('func: ',args.func)
else:
    print('func not defined')

示例运行:

2020:~/mypy$ python3 stack56435945.py 
usage: stack56435945.py [-h] [-v] {subcommand} ...
stack56435945.py: error: the following arguments are required: action

2021:~/mypy$ python3 stack56435945.py subcommand
usage: stack56435945.py subcommand [-h] {subsubcommand1,subsubcommand2} ...
stack56435945.py subcommand: error: the following arguments are required: subaction

2021:~/mypy$ python3 stack56435945.py subcommand subsubcommand1 --arg1 foobar
Namespace(action='subcommand', arg1='foobar', arg2='hello', func='mylib.subsub1', subaction='subsubcommand1', v=False)
func:  mylib.subsub1

2022:~/mypy$ python3 stack56435945.py subcommand subsubcommand2
Namespace(action='subcommand', subaction='subsubcommand2', v=False)
func not defined