Argparse: two positional arguments with nargs = '+'

I am trying to perform math operations between images. I defined (a simplified version of my real code):

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', action='store', type=str, 
      help='type of operation (+,-,*,/) to be done', nargs=1)
parser.add_argument("input2",metavar='input2', action='store', nargs="+", 
      type=str, help='image (or value) with which to perform the operation on input1')

This code produces:

arith.py -h
usage: arith.py [-h] input1 [input1 ...] operation input2 [input2 ...]

therefore, he understands that input1 can contain one or more elements, the operation will be one, and input2 can be any number of elements.

The problem, of course, is that having two positional arguments with an indefinite number of elements argparse confuses what is. I tried to add the options = ["+", "-", "*", "/"] to the "operation" so that it knew where to split, but it seems argparse cannot do this. In fact, in the argparse documentation talking about nargs = '*', you can read:

, nargs = '*'

, args.input1, args.operation args.input2 "+", "-", "/", "*", - . , .

+4
2

, char (, '-'), . , "" , "". :

re.match('(A+)(A)(A+)','AAAAAAAAA')

(AAAAAA),(A),(A). , , .

, - "", .

, , argparse:

parser.add_argument("input1", nargs="+", type=int)
parser.add_argument("-o", "--operation", choices=['+','minus','*','/'] )
parser.add_argument("input2", nargs="+", 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])

, choices '-'. , prefix_char. , , .

input1 . . , , .

, type=str, action='store'.


, , 1 . , argparse.

alist = ['1','2','3','+','4','5','6']
i = <find index of '+-/*'>
input1 = alist[:i]
operations = alist[i]
input2 = alsits[i+1:]
+1

" " , . . .

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument("--left-operands", "-l", nargs="+", required=True)
parser.add_argument("--right-operands", "-r", nargs="+", required=True)
parser.add_argument("--operation", "-o", choices=["+", "-", "*", "/"], required=True)

argline = "-l 1 2 -o + -r 3 4"

print(parser.parse_args(argline.split(" ")))
0

All Articles