如何使用python argparse解析多个嵌套的子命令? [英] How to parse multiple nested sub-commands using python argparse?

查看:38
本文介绍了如何使用python argparse解析多个嵌套的子命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个命令行程序,它有这样的界面:

I am implementing a command line program which has interface like this:

cmd [GLOBAL_OPTIONS] {command [COMMAND_OPTS]} [{command [COMMAND_OPTS]} ...]

我已经阅读了 argparse 文档.我可以使用 argparse 中的 add_argumentGLOBAL_OPTIONS 实现为可选参数.而 {command [COMMAND_OPTS]} 使用 子命令.

I have gone through the argparse documentation. I can implement GLOBAL_OPTIONS as optional argument using add_argument in argparse. And the {command [COMMAND_OPTS]} using Sub-commands.

从文档看来我只能有一个子命令.但是正如您所看到的,我必须实现一个或多个子命令.使用 argparse 解析此类命令行参数的最佳方法是什么?

From the documentation it seems I can have only one sub-command. But as you can see I have to implement one or more sub-commands. What is the best way to parse such command line arguments useing argparse?

推荐答案

@mgilson 对这个问题有一个很好的答案.但是我自己拆分 sys.argv 的问题是我丢失了 Argparse 为用户生成的所有好的帮助消息.所以我最终这样做了:

@mgilson has a nice answer to this question. But problem with splitting sys.argv myself is that i lose all the nice help message Argparse generates for the user. So i ended up doing this:

import argparse

## This function takes the 'extra' attribute from global namespace and re-parses it to create separate namespaces for all other chained commands.
def parse_extra (parser, namespace):
  namespaces = []
  extra = namespace.extra
  while extra:
    n = parser.parse_args(extra)
    extra = n.extra
    namespaces.append(n)

  return namespaces

argparser=argparse.ArgumentParser()
subparsers = argparser.add_subparsers(help='sub-command help', dest='subparser_name')

parser_a = subparsers.add_parser('command_a', help = "command_a help")
## Setup options for parser_a

## Add nargs="*" for zero or more other commands
argparser.add_argument('extra', nargs = "*", help = 'Other commands')

## Do similar stuff for other sub-parsers

现在在第一次解析后,所有链接的命令都存储在 extra 中.当它不为空时,我重新解析它以获取所有链接的命令并为它们创建单独的命名空间.我得到了 argparse 生成的更好的用法字符串.

Now after first parse all chained commands are stored in extra. I reparse it while it is not empty to get all the chained commands and create separate namespaces for them. And i get nicer usage string that argparse generates.

这篇关于如何使用python argparse解析多个嵌套的子命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆