I have to miss something obvious. The goal is to use argparse with the first parameter required, the second optional and any other remaining parameters.
To show the problem, I made two test analyzers; the only difference between the two is the use of nargs = argparse.REMAINDER in one and nargs = '*' in the other.
def doParser1(argsin): parser = argparse.ArgumentParser(description='Parser demo.') parser.add_argument('req1', help='first required parameter') parser.add_argument('--opt1', help='first optional parameter') parser.add_argument('leftovers', nargs=argparse.REMAINDER, help='all the other parameters') argsout = parser.parse_args(args=argsin) print argsout return argsout def doParser2(argsin): parser = argparse.ArgumentParser(description='Parser demo.') parser.add_argument('req1', help='first required parameter') parser.add_argument('--opt1', help='first optional parameter') parser.add_argument('leftovers', nargs='*', help='all the other parameters') argsout = parser.parse_args(args=argsin) print argsout return argsout
If there are no additional parameters, then parser2 works. This is the input followed by parser1 and parser 1:
input: ['req1value', '--opt1', 'opt1value'] Namespace(leftovers=['--opt1', 'opt1value'], opt1=None, req1='req1value') Namespace(leftovers=None, opt1='opt1value', req1='req1value')
If there are additional parameters, opt1 is omitted in parser1, and parser2 is simply confused:
input: ['req1value', '--opt1', 'opt1value', 'r1', 'r2'] Namespace(leftovers=['--opt1', 'opt1value', 'r1', 'r2'], opt1=None, req1='req1value') usage: py-argparse.py [-h] [--opt1 OPT1] [-leftovers [LEFTOVERS [LEFTOVERS ...]]] req1 py-argparse.py: error: unrecognized arguments: r1 r2
The expected result should be:
Namespace(leftovers=['r1', 'r2'], opt1='opt1value', req1='req1value')
It seems that this should be a simple case, and what is here is simplified from what I'm really trying to do. I tried to make the rest extra, adding a lot of other options, but nothing improved.
Any help would be appreciated.