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

查看:232
本文介绍了如何使用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天全站免登陆