Argparse: How To Separate Unknown(and Optional) Args When Subparsers Are Present.(subparsers Are Also Optional)
I have the following code parser = argparse.ArgumentParser(allow_abbrev=False, add_help=False) parser.add_argument('--conf', nargs=1) parser.add_argument('-h', '--help', nargs='?',
Solution 1:
As I wrote in a comment, subparsers is a positional argument.
To illustrate with a plain positional:
In [307]: parser = argparse.ArgumentParser()
In [308]: a1 = parser.add_argument('foo')
In [309]: parser.parse_known_args(['one','two'])
Out[309]: (Namespace(foo='one'), ['two'])
'one' is allocated to the first positional. Now give foo
choices:
In [310]: a1.choices = ['bar','test']
In [311]: parser.parse_known_args(['one','two'])
usage: ipython3 [-h] {bar,test}
ipython3: error: argument foo: invalid choice: 'one' (choose from 'bar', 'test')
It is still trying to allocate the first string to foo
. Since it doesn't match choices
, it raises an error.
In [312]: parser.parse_known_args(['bar','one','two'])
Out[312]: (Namespace(foo='bar'), ['one', 'two'])
Strings are assigned to positionals based on position, not on value. Any value checking, such as with type or choices is done after assignment.
Change the choices
to a type
test:
In [313]: a1.choices = None
In [314]: a1.type = int
In [315]: parser.parse_known_args(['bar','one','two'])
usage: ipython3 [-h] foo
ipython3: error: argument foo: invalid int value: 'bar'
In [316]: parser.parse_known_args(['12','one','two'])
Out[316]: (Namespace(foo=12), ['one', 'two'])
Post a Comment for "Argparse: How To Separate Unknown(and Optional) Args When Subparsers Are Present.(subparsers Are Also Optional)"