parser = argparse.ArgumentParser(description='Arithmetic operations on images') parser.add_argument("input1",metavar='input1',action='store',help='list of input images to operate with',nargs="+",type=str) parser.add_argument("operation",metavar='operation',type=str,help='type of operation (+,-,*,/) to be done',nargs=1) parser.add_argument("input2",metavar='input2',help='image (or value) with which to perform the operation on input1')
这段代码产生:
arith.py -h usage: arith.py [-h] input1 [input1 ...] operation input2 [input2 ...]
所以它确实理解input1可以包含一个或多个元素,操作将是单个元素,input2可以是任意数量的元素.
当然,问题在于,有两个位置参数和不确定数量的元素,argparse会混淆什么.我已经尝试将choices = [“”,“ – ”,“*”,“/”]添加到’operation’,以便它知道在哪里进行分离,但似乎argparse无法做到.实际上,在argparse文档中,谈论nargs =’*’你可以读到:
Note that it generally doesn’t make much sense to have more than one positional argument with nargs=’*’
我原以为我可以将args.input1,args.operation和args.input2加在一起,并将自己分开寻找“”,“/”,但在做一些如此丑陋的事情之前我想过点击集体思想.
解决方法
re.match('(A+)(A)(A+)','AAAAAAAAA')
会产生(AAAAAA),(A),(A).它为最后两组分配足够的字符串以满足其规范,并将其余组分配给第一组.
所以你需要某种“标志”来标记第一个列表的结尾.
我认为,这是你与argparse最接近的:
parser.add_argument("input1",type=int) parser.add_argument("-o","--operation",choices=['+','minus','*','/'] ) parser.add_argument("input2",type=int)
哪个应该转
PROG 1 3 4 -o + 5 6 7 PROG 1 3 4 -o+ 5 6 7 PROG 1 3 4 --operation=+ 5 6 7
进入(我认为)
namespace(input1=[1,3,4],operation='+',input2=[5,6,7])
请注意,选择列表不包括“ – ”.那是因为解析器将其视为prefix_char.可能有一种方法可以将其作为参数值隐藏,但我不会花时间找到它.
我将input1值转换为解析器中的整数.你可以在那之后做到.当然还要制作花车.
我省略了默认参数,如type = str,action =’store’.
但也许更好的解决方案是将所有值作为1个列表,并自行拆分.至少有这3个参数你没有多少使用argparse功能.
alist = ['1','2','3','+','4','5','6'] i = <find index of '+-/*'> input1 = alist[:i] operations = alist[i] input2 = alsits[i+1:]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。