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

查看:33
本文介绍了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 不同,`positional 只作用一次.

  • 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天全站免登陆