Python:argparse subcommand 子命令?

2022-01-21 00:00:00 python argparse arguments

问题描述

我的程序有很多可用选项.例如用于更改设置的配置选项.

I have a program that has many available options. For example a configuration option to change settings.

./app config -h

使用普通的 argparse 子命令帮助我

gives me the help using normal argparse subcommands

现在我想在名为 list 的配置子命令中添加另一个子命令以列出配置值

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

./app config list

此外,该命令应该接受另一个选项,以便我可以说

additionally that command should accept another option so that i could say

./app config list CATEGORY

只列出一个类别的配置

我现在的代码基本上就是这样,只是有更多的命令

my code right now is basically this just with more 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 a subcommand in a subcommand. If this is possible, how? If not, is there any other way to accomplish this goal?

提前致谢


解决方案

#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')

似乎有效.

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)

相关文章