如何在python中创建类似adb shell的参数解析器?

如何在python中创建类似adb shell的参数解析器?,python,parsing,command-line-arguments,argparse,Python,Parsing,Command Line Arguments,Argparse,adb外壳am具有如下参数: [--eia <EXTRA_KEY> <EXTRA_INT_VALUE>[,<EXTRA_INT_VALUE...]] 但我看不出这些是否也适用于可选参数 根据我的要求,从argparse开始是个好主意吗?还有其他选择吗 - consists of 2 or more arguments (eg. --eia key1 1 2 3) (see last point) 有一个建议的补丁,允许类似于2个或更多的nargs,以re{n,

adb外壳am
具有如下参数:

 [--eia <EXTRA_KEY> <EXTRA_INT_VALUE>[,<EXTRA_INT_VALUE...]]
但我看不出这些是否也适用于可选参数

根据我的要求,从
argparse
开始是个好主意吗?还有其他选择吗

- consists of 2 or more arguments (eg. --eia key1 1 2 3) (see last point)
有一个建议的补丁,允许类似于
2个或更多
nargs
,以
re{n,m}
符号为模型。但现在我认为,
nargs='+'
是你最好的选择。重要的是它抓住了必要的论点。您可以在
parse_args
之后检查“2或更多”(自定义
类型也可以检查)

使用
--eia
标志可以解决这个问题

- edit it can occour multiple times, eg. --eia key1 1,2 --eia key2 2,1 is valid
使用允许的
--eia
标志,但只保留最后一个条目。但是
action='append'
会将每个条目集保存为一个列表(或元组?);因此,名称空间将具有
args.eia=['key1'、'1'、'2']、['key2'、…]、…]
。使用动作类型进行游戏并验证此操作

- the type of the first argument may differ from the type of the rest
将值保留为字符串,然后进行自己的转换是最简单的。您可以编写自定义的
类型
(或
操作
)来检查值。但是代码将类似于在
argparse
之后使用的代码

- other optional arguments like this can exist
这将取决于您如何编写添加的代码

- the example has the delimiter of a , but I'd like to allow delimiting with spaces, because my actual argument values may be strings and I'd like to leave parsing them to the shell (if a string should start with -, quotation marks help: "-asdf")
主shell(调用脚本的shell)将命令行拆分为字符串,主要是在空格上
argparse
使用字符串列表
sys.argv
。如果该列表不是您想要的,那么在将其传递给
argparse.parse_args(argv)
之前,您必须对其进行修改

测试
argparse
的常用方法是:

parser.parse_args('--eia key1 1,2 --eia key2 2,1'.split())
复制空格上的主拆分,但不像shell那样处理引号和转义字符。有一种复制shell操作的方法,但我必须四处挖掘才能找到它

- the example has the delimiter of a , but I'd like to allow delimiting with spaces, because my actual argument values may be strings and I'd like to leave parsing them to the shell (if a string should start with -, quotation marks help: "-asdf")
parser.parse_args('--eia key1 1,2 --eia key2 2,1'.split())