Python argparse将位置参数导入多个列表

Python argparse将位置参数导入多个列表,python,argparse,Python,Argparse,我希望能够支持基于先前谓词进入不同列表的位置命令行参数 例如,类似以下命令的命令: mycommand one two three mycommand one --other two three --main four five 将生成如下参数: main_dest = ['one','two','three'] other_dest = [] main_dest = ['one','four','five'] other_dest = ['two','three'] 但是像这样的命令:

我希望能够支持基于先前谓词进入不同列表的位置命令行参数

例如,类似以下命令的命令:

mycommand one two three
mycommand one --other two three --main four five
将生成如下参数:

main_dest = ['one','two','three']
other_dest = []
main_dest = ['one','four','five']
other_dest = ['two','three']
但是像这样的命令:

mycommand one two three
mycommand one --other two three --main four five
将生成如下参数:

main_dest = ['one','two','three']
other_dest = []
main_dest = ['one','four','five']
other_dest = ['two','three']

从概念上讲,我想要的是修改位置参数读取器的
dest
的操作。

作为第一次尝试,这组操作似乎起到了作用:

In [73]: parser = argparse.ArgumentParser()
In [74]: parser.add_argument('main', nargs='*');
In [75]: parser.add_argument('other', nargs='*');
In [76]: parser.add_argument('--main', action='append');
In [77]: parser.add_argument('--other', action='append');

In [78]: parser.print_usage()
usage: ipython3 [-h] [--main MAIN] [--other OTHER]
                [main [main ...]] [other [other ...]]

In [79]: parser.parse_args('one two three'.split())
Out[79]: Namespace(main=['one', 'two', 'three'], other=[])

In [80]: parser.parse_args('one --other two --main three'.split())
Out[80]: Namespace(main=['one', 'three'], other=['two'])
74和76都将
main
作为其
dest
。我使用
append
来添加标记的位置值,这样它们就不会覆盖位置值。但是,不管
用法显示了什么,位置只能在开始时起作用。如果在末端放置一个标记,它们将覆盖标记的值。“其他”位置永远不会得到值-所以我应该忽略它

所以,玩这样的游戏是可能的,但我不确定它是否健壮,或者对用户来说是否更容易


作为第一次尝试,这组操作似乎达到了目的:

In [73]: parser = argparse.ArgumentParser()
In [74]: parser.add_argument('main', nargs='*');
In [75]: parser.add_argument('other', nargs='*');
In [76]: parser.add_argument('--main', action='append');
In [77]: parser.add_argument('--other', action='append');

In [78]: parser.print_usage()
usage: ipython3 [-h] [--main MAIN] [--other OTHER]
                [main [main ...]] [other [other ...]]

In [79]: parser.parse_args('one two three'.split())
Out[79]: Namespace(main=['one', 'two', 'three'], other=[])

In [80]: parser.parse_args('one --other two --main three'.split())
Out[80]: Namespace(main=['one', 'three'], other=['two'])
74和76都将
main
作为其
dest
。我使用
append
来添加标记的位置值,这样它们就不会覆盖位置值。但是,不管
用法显示了什么,位置只能在开始时起作用。如果在末端放置一个标记,它们将覆盖标记的值。“其他”位置永远不会得到值-所以我应该忽略它

所以,玩这样的游戏是可能的,但我不确定它是否健壮,或者对用户来说是否更容易


我编辑了我的问题,以便更清楚地表明我希望在流拆分之后可能有多个参数。我以前尝试过这个解决方案,不幸的是,甚至在
main
other
参数中添加
nargs
都没有实际的帮助(IIRC我得到了一个列表结果或类似的奇怪结果)。你可以稍后将列表展平。您还可以在使用list extend的append操作上编写变体。可能还需要对action类进行其他自定义。其他argparse答案以各种方式自定义了Action类。我编辑了我的问题,以便更清楚地表明我希望在流拆分之后可能有多个参数。我以前尝试过这个解决方案,不幸的是,甚至在
main
other
参数中添加
nargs
都没有实际的帮助(IIRC我得到了一个列表结果或类似的奇怪结果)。你可以稍后将列表展平。您还可以在使用list extend的append操作上编写变体。可能还需要对action类进行其他自定义。其他argparse答案以各种方式自定义了Action类。