Skip to content
Advertisement

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?

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement