Using Argparse.remainder At Beginning Of Parser / Sub Parser
Solution 1:
Looks like the same issue discussed in http://bugs.python.org/issue17050, argparse.REMAINDER doesn't work as first argument
My deduction from 4 years ago still holds - the -blah
is being classed as an optional's flag even before REMAINDER
has a chance to act. '--' is parsed earlier, but ...
is, in a sense just a generalization of '*'. And not a widely used one. For what it's worth the 'subparsers' Action has a nargs='+...'
value (argparse.PARSER
) - it's like REMAINDER except it requires at least one string, the 'cmd'.
The possible fix in http://bugs.python.org/issue9334 has not been acted on. So you either need to handle the '-blah' by itself, or use '--'. parse_known_args
might also work in your case.
Solution 2:
As noted, the existing behavior is bad. One workaround is to implement a simple
ArgumentParser
subclass and use that for your subparser:
classSubcommandParser(argparse.ArgumentParser):
"""This subparser puts all remaining arguments in args attribute of namespace"""defparse_known_args(self, args=None, namespace=None):
if namespace isNone:
namespace = argparse.Namespace()
setattr(namespace, 'args', args)
return namespace, []
...
p.add_subparsers(dest='cmd', parser_class=SubcommandParser)
Post a Comment for "Using Argparse.remainder At Beginning Of Parser / Sub Parser"