Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop parsing on first unknown argument

Using argparse, is it possible to stop parsing arguments at the first unknown argument?

I've found 2 almost solutions;

  1. parse_known_args, but this allows for known parameters to be detected after the first unknown argument.
  2. nargs=argparse.REMAINDER, but this won't stop parsing until the first non-option argument. Any options preceding this that aren't recognised generate an error.

Have I overlooked something? Should I be using argparse at all?

like image 359
Matt Joiner Avatar asked Jul 14 '11 01:07

Matt Joiner


1 Answers

I haven't used argparse myself (need to keep my code 2.6-compatible), but looking through the docs, I don't think you've missed anything.

So I have to wonder why you want argparse to stop parsing arguments, and why the -- pseudo-argument won't do the job. From the docs:

If you have positional arguments that must begin with '-' and don’t look like negative numbers, you can insert the pseudo-argument '--' which tells parse_args() that everything after that is a positional argument:

>>> parser.parse_args(['--', '-f'])
Namespace(foo='-f', one=None)
like image 85
Mike DeSimone Avatar answered Oct 23 '22 06:10

Mike DeSimone