argparse:让相同的必需参数是位置或可选的 [英] argparse: let the same required argument be positional OR optional
问题描述
我希望将必需的命令行参数作为位置参数或可选参数传递.例如,我希望从以下任何调用中执行相同的操作:
I would like to have a required command line argument passed as a positional argument or an optional argument. For example, I would like the same action be performed from any of the following invocations:
prog 10
prog -10
prog -n 10
prog --num 10
这可以通过 argparse 实现吗?
Is this possible with argparse?
推荐答案
使用互斥组我可以创建一个合理的近似:
With a mutually exclusive group I can create a reasonable approximation:
在交互式会话中:
In [10]: parser=argparse.ArgumentParser()
In [11]: grp=parser.add_mutually_exclusive_group(required=True)
In [12]: a=grp.add_argument('pos',nargs='?',type=int,default=0)
In [13]: b=grp.add_argument('-n','--num')
grp
可以包含任意数量的可选和一个可选的位置.我为位置选择了不同的 type
只是为了突出差异.
grp
can contain any number of optionals, and one optional positional. I chose a different type
for the positional just a highlight the difference.
只是位置值:
In [14]: parser.parse_args(['10'])
Out[14]: Namespace(num=None, pos=10)
各种形式的可选:
In [16]: parser.parse_args(['-n10'])
Out[16]: Namespace(num='10', pos=0)
In [17]: parser.parse_args(['--num=10'])
Out[17]: Namespace(num='10', pos=0)
In [18]: parser.parse_args(['--num','10'])
Out[18]: Namespace(num='10', pos=0)
测试组独占性
In [25]: parser.parse_args(['--num=20','10'])
usage: ipython3 [-h] [-n NUM] [pos]
ipython3: error: argument pos: not allowed with argument -n/--num
和需要的组:
In [26]: parser.parse_args([])
usage: ipython3 [-h] [-n NUM] [pos]
ipython3: error: one of the arguments pos -n/--num is required
我尝试为位置提供与可选相同的 dest
- 这样两者都会写入 num
.但这会导致位置覆盖使用默认值写入 dest
(如果需要,我可以添加详细信息)
I experimented with giving the positional the same dest
as the optional - so both would write to num
. But this results in the positional over writing the dest
with its default (I can add details if needed)
In [19]: a.dest
Out[19]: 'pos'
In [20]: a.dest='num'
In [21]: parser.parse_args(['--num','10'])
Out[21]: Namespace(num=0)
后解析代码必须以任何有意义的方式处理 args.pos
和 args.num
值.
Post parsing code will have to handle the args.pos
and args.num
values in what ever way makes sense.
'-10
' 输入无法处理.好吧,我可以定义:
The '-10
' input is impossible to handle. Well, I could define:
parser.add_argument('-1')
但结果可能不是你想要的:
but the result is probably not what you want:
In [31]: parser.parse_args(['--num=20','-12'])
Out[31]: Namespace(1='2', num='20', pos=0)
总的来说,这个要求给程序员带来了不必要的困难.
Overall this requirement makes things unnecessarily difficult for you the programmer.
这篇关于argparse:让相同的必需参数是位置或可选的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!