How to handle CLI subcommands with argparse

╄→гoц情女王★ 提交于 2019-11-28 11:33:00

First of all subparsers are never inserted in the namespace. In the example you posted if you try to run the script as:

$python3 test_args.py cmd1 1
Namespace(cmd1_option1='1')

where test_args.py contain the code you provided (with the import argparse at the beginning and print(args) at the end).

Note that there is no mention to cmd1 only to its argument. This is by design.

As pointed out in the comments you can add that information passing the dest argument to the add_subparsers call.

The usual way to handle these circumstances is to use the set_defaults method of the subparsers:

import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='Functions')
parser_1 = subparsers.add_parser('cmd1', help='...')
parser_1.add_argument('cmd1_option1', type=str, help='...')
parser_1.set_defaults(parser1=True)

parser_2 = subparsers.add_parser('cmd2', help='...')
parser_2.set_defaults(parser2=True)

parser_3 = subparsers.add_parser('cmd3', help='...')
parser_3.add_argument('cmd3_options', type=int, help='...')
parser_3.set_defaults(parser_3=True)

args = parser.parse_args()
print(args)

Which results in:

$python3 test_args.py cmd1 1
Namespace(cmd1_option1='1', parser1=True)
$python3 test_args.py cmd2
Namespace(parser2=True)

In general different subparser will, most of the time, handle the arguments in completely different ways. The usual pattern is to have different functions to run the different commands and use set_defaults to set a func attribute. When you parse the arguments you simply call that callable:

subparsers = parser.add_subparsers()
parser_1 = subparsers.add_parser(...)
parser_1.set_default(func=do_command_one)

parser_k = subparsers.add_parser(...)
parser_k.set_default(func=do_command_k)

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

The subparser identity can be added to the main Namespace if the add_subparsers command is given a dest.

From the documentation:

However, if it is necessary to check the name of the subparser that was invoked, the dest keyword argument to the add_subparsers() call will work:

>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers(dest='subparser_name')
>>> subparser1 = subparsers.add_parser('1')
>>> subparser1.add_argument('-x')
>>> subparser2 = subparsers.add_parser('2')
>>> subparser2.add_argument('y')
>>> parser.parse_args(['2', 'frobble'])
Namespace(subparser_name='2', y='frobble')

By default the dest is argparse.SUPPRESS, which keeps subparsers from adding the name to the namespace.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!