Python:argparse subcommand 子命令?

Python: argparse subcommand subcommand?(Python:argparse subcommand 子命令?)
本文介绍了Python:argparse subcommand 子命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

这篇关于Python:argparse subcommand 子命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)