开发者

Stop parsing on first unknown argument

开发者 https://www.devze.com 2023-03-20 08:25 出处:网络
Using argparse, is it possible to stop parsing arguments at the first unknown argument? I\'v开发者_JS百科e found 2 almost solutions;

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

I'v开发者_JS百科e 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?


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)


One way to do it, although it may not be perfect in all situations, is to use getopt instead.

for example:

import sys
import os
from getopt import getopt


flags, args = getopt(sys.argv[1:], 'hk', ['help', 'key='])

for flag, v in flags:
    if flag in ['-h', '--help']:
        print(USAGE, file=sys.stderr)
        os.exit()
    elif flag in ['-k', '--key']:
        key = v

Once getopt encounters a non-option argument it will stop processing arguments.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号