Argparse:解析多个子命令 [英] Argparse: parse multiple subcommands

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

问题描述

进行了一些研究,但找不到任何可行的解决方案.我正在尝试解析以下命令行,其中"test"和"train"是两个独立的子命令,每个子命令具有不同的参数:

Did some research, but couldn't find any working solution. I'm trying to parse the following command line, where 'test' and 'train' are two independent subcommands each having distinct arguments:

./foo.py train -a 1 -b 2 
./foo.py test  -a 3 -c 4
./foo.py train -a 1 -b 2 test -a 3 -c 4

我一直在尝试使用两个子解析器("test","train"),但似乎当时只能解析一个.同样重要的是让主解析器的那些子解析器的父级例如不必将命令"-a"同时添加到子解析器"train"和"test"中

I've been trying using two subparsers ('test','train') but it seems like only one can be parsed at the time. Also it would be great to have those subparsers parents of the main parser such that, e.g. command '-a' doesn't have to be added both to the subparsers 'train' and 'test'

有解决方案吗?

推荐答案

尽管我不确定找到这些问题的最佳方法,但这已被问过.

This has been asked before, though I'm not sure the best way of finding those questions.

整个子解析器机制是为一种这样的命令设计的.有几件事要注意:

The whole subparser mechanism is designed for one such command. There are several things to note:

  • add_subparsers创建一个位置参数;与optionals不同,`位置仅作用一次.

  • add_subparsers creates a positional argument; unlike optionals a `positional acts only once.

'add_subparsers'如果多次调用,则会引发错误

'add_subparsers' raises an error if you invoke it several times

仅围绕一个这样的调用构建解析

the parsing is built around only one such call

我们过去提出的一种解决方法是嵌套"或递归"子配置器.换句话说,设置了train,因此它也需要一个子解析器.但是,是否需要次级解析器就很麻烦.

One work around that we've proposed in the past is 'nested' or 'recursive' subparers. In other words train is setup so it too takes a subparser. But there's the complication as to whether subparsers are required or not.

或者您可以绕过subparser机制来检测并调用多个解析器.

Or you can detect and call multiple parsers, bypassing the subparser mechanism.

从侧边栏

在同一时间多次调用同一子命令单个命令行

在python中解析多个子命令同时或以其他方式将解析后的参数分组

这篇关于Argparse:解析多个子命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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