I want to get all the remaining unused arguments at once. How do I do it?
parser.add_argument('-i', action='store', dest='i', default='i.log')
parser.add_argument('-o', action='store', dest='o', default='o.log')
I want to get all the remaining unused arguments at once. How do I do it?
parser.add_argument('-i', action='store', dest='i', default='i.log')
parser.add_argument('-o', action='store', dest='o', default='o.log')
I went and coded up the three suggestions given as answers in this thread. The test code appears at the bottom of this answer. Conclusion: The best all-around answer so far is
nargs=REMAINDER
, but it might really depend on your use case.Here are the differences I observed:
(1)
nargs=REMAINDER
wins the user-friendliness test.(2)
nargs=*
quietly filters out the first--
argument on the command line, which seems bad. On the other hand, all methods respect--
as a way to say "please don't parse any more of these strings as known args."(3) Any method except
parse_known_args
dies if it tries to parse a string beginning with-
and it turns out not to be valid.(4)
nargs=REMAINDER
completely stops parsing when it hits the first unknown argument.parse_known_args
will gobble up arguments that are "known", no matter where they appear on the line (and will die if they look malformed).Here's my test code.
Use
parse_known_args()
:Use
argparse.REMAINDER
:Example:
Another option is to add a positional argument to your parser. Specify the option without leading dashes, and
argparse
will look for them when no other option is recognized. This has the added benefit of improving the help text for the command:and