停止解析第一个未知参数

发布于 2024-11-24 10:33:18 字数 608 浏览 4 评论 0原文

使用 argparse 是否可以停止解析参数在第一个未知的论点?

我找到了两个几乎解决方案;

  1. parse_known_args,但是这个允许在第一个未知参数之后检测已知参数。
  2. nargs=argparse.REMAINDER ,但这不会停止解析,直到第一个非选项参数。在此之前的任何无法识别的选项都会生成错误。

我是不是忽略了什么?我应该使用 argparse 吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笛声青案梦长安 2024-12-01 10:33:18

我自己没有使用过 argparse(需要保持我的代码与 2.6 兼容),但是浏览文档,我认为您没有错过任何内容。

所以我想知道为什么你希望 argparse 停止解析参数,以及为什么 -- 伪参数不能完成这项工作。 来自文档:

如果您的位置参数必须以 '-' 开头,并且看起来不像负数,则可以插入伪参数 '--'告诉 parse_args() 之后的所有内容都是位置参数:

>>> parser.parse_args(['--', '-f'])
Namespace(foo='-f', one=None)

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)
情深已缘浅 2024-12-01 10:33:18

一种方法是使用 getopt 来代替,尽管它可能并不适合所有情况。

例如:

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

一旦 getopt 遇到非选项参数,它将停止处理参数。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文