argparse:让相同的必需参数为位置或可选 [英] argparse: let the same required argument be positional OR optional

查看:103
本文介绍了argparse:让相同的必需参数为位置或可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将必需的命令行参数作为位置参数或可选参数传递.例如,我希望从以下任何调用中执行相同的操作:

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.posargs.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屋!

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