Python subcommand subcommand: argparse?

I have a program that has many options available. For example, a configuration parameter for changing settings.

./app config -h 

gives me help using regular argparse subcommands

now I would like to add another subcommand to the config subcommand called list to list config values

 ./app config list 

in addition, this command must accept another option so that I can say

 ./app config list CATEGORY 

only to display the configuration of one category

my code right now basically it's just with lots of commands

 >>> parser = argparse.ArgumentParser() >>> subparsers = parser.add_subparsers(title='subcommands', ... description='valid subcommands', ... help='additional help') >>> subparsers.add_parser('foo') >>> subparsers.add_parser('bar') >>> parser.parse_args(['-h']) usage: [-h] {foo,bar} ... optional arguments: -h, --help show this help message and exit subcommands: valid subcommands {foo,bar} additional help 

So far, I could not find any way to use the subcommand in the subcommand. If possible, how? If not, is there any other way to achieve this?

Thanks at Advance

+6
source share
1 answer
 #file: argp.py import argparse parser = argparse.ArgumentParser(prog='PROG') parser_subparsers = parser.add_subparsers() sub = parser_subparsers.add_parser('sub') sub_subparsers = sub.add_subparsers() sub_sub = sub_subparsers.add_parser('sub_sub') sub_sub_subparsers = sub_sub.add_subparsers() sub_sub_sub = sub_sub_subparsers.add_parser('sub_sub_sub') 

Seems to work.

 In [392]: run argp.py In [393]: parser.parse_args('sub sub_sub sub_sub_sub'.split()) Out[393]: Namespace() In [400]: sys.version_info Out[400]: sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) 
+8
source

Source: https://habr.com/ru/post/902998/


All Articles