如何让 argparse 接受“--”作为选项的参数?

How can I get argparse to accept "--" as an argument to an option?

我有一个需要参数的命令行选项。我希望能够提供 "--" 作为参数,但我不知道该怎么做。

示例代码:(test-argparse.py)

#!/usr/bin/env python

from __future__ import print_function
import argparse
import sys


def main(argv):
    ap = argparse.ArgumentParser()
    ap.add_argument("-x", "--foo", metavar="VALUE", default="",
                    help="Test option.")
    args = ap.parse_args(argv[1:])

    print(args.foo)

if __name__ == "__main__":
    sys.exit(main(sys.argv))

我所有尝试将 "--" 作为参数传递的尝试都失败了:

$ test-argparse.py --foo --
usage: test-argparse.py [-h] [-x VALUE]
test-argparse.py: error: argument -x/--foo: expected one argument

$ test-argparse.py --foo -- --
usage: test-argparse.py [-h] [-x VALUE]
test-argparse.py: error: argument -x/--foo: expected one argument

$ test-argparse.py --foo=--
[]

$ test-argparse.py --foo=-- --
usage: test-argparse.py [-h] [-x VALUE]
test-argparse.py: error: unrecognized arguments: --

$ test-argparse.py --foo="--"
[]

$ test-argparse.py '--foo --'
usage: test-argparse.py [-h] [-x VALUE]
test-argparse.py: error: unrecognized arguments: --foo --

$ test-argparse.py -x--
[]

$ test-argparse.py '-x --'
 --

最后一种情况最接近,但它包括 space(我不能只去掉白色 space,因为如果我想允许 " " 作为价值?)。有什么办法可以做到这一点吗?

argparse 强制对客户端进行参数排列(导致不必要的歧义)非常令人沮丧。

(我正在使用 Python 2.7.12。)

这不起作用有一个特定原因:-- 表示 "Skip this token and consider the rest of the arguments to be positional, even if they start with a dash."

很多很多程序不会接受 -- 作为参数,但它们会接受 -。单破折号甚至是指定 "Use standard input or output" 代替文件名的标准方式。

因此,您可以为程序的用户做的最好的事情可能就是不要将其设计为需要 --,因为这不是通常要做的事情,也不是大多数现代命令行解析的事情库可能能够解析。

你可以使用 -- 作为位置选项,所以你可能会支持这个:

--foo -- --

如果你让 --fooaction='store_true'(即它是一个不带参数的选项),加上一个非强制性位置参数。这可能会起作用,因为第一个 -- 表示 "stop processing dashes as options" 而第二个是位置参数。

理想情况下 --foo=-- 应该可以工作,但当前的解析器会删除所有“--”,在其位置留下一个空字符串,因此会出现 foo=[] 结果。几年前我提出了一个本应修复该问题的补丁,但它陷入了 argparse 待办事项列表中。 http://bugs.python.org/issue13922, http://bugs.python.org/issue14364, http://bugs.python.org/issue9571

建议预处理 sys.argv 用其他东西替换一个或多个 --

如果您喜欢修补 argparse.py 文件(或子class ArgumentParser class),我可以重温我之前的工作并提出修复建议。诀窍是接受 =-- 但仍然使用第一个空闲 -- 作为 'rest-are-positionals' 标志(并保留任何后续 --)。不幸的是,一个需要修补的方法嵌套在一个更大的方法中。