【问题标题】:Python argparse: Leading dash in argumentPython argparse:参数中的前导破折号
【发布时间】:2019-03-09 05:33:04
【问题描述】:

我正在使用 Python 的 argparse 模块来解析命令行参数。考虑以下简化示例,

# File test.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-s', action='store')
parser.add_argument('-a', action='append')
args = parser.parse_args()
print(args)

可以像这样成功调用

python test.py -s foo -a bar -a baz

-s 和每个-a 之后都需要一个参数,如果我们使用引号,则可能包含空格。但是,如果参数以破折号 (-) 开头并且不包含任何空格,则代码会崩溃:

python test.py -s -begins-with-dash -a bar -a baz

错误:参数 -s:需要一个参数

我知道它将-begins-with-dash 解释为新选项的开始,这是非法的,因为-s 尚未收到其所需的参数。虽然没有定义名称为 -begins-with-dash 的选项,但也很清楚,因此它不应该首先将其解释为选项。如何让argparse 接受带有一个或多个前导破折号的参数?

【问题讨论】:

标签: python python-3.x parsing command-line-arguments argparse


【解决方案1】:

您可以通过包含等号来强制 argparse 将参数解释为值: python test.py -s=-begins-with-dash -a bar -a baz Namespace(a=['bar', 'baz'], s='-begins-with-dash')

【讨论】:

  • 没错,虽然我真正想要的是 Python 脚本中的解决方案,允许像 -s -begins-with-dash 一样调用它。
【解决方案2】:

如果您尝试为一个参数提供多个值:

parser.add_argument('-a', action='append', nargs=argparse.REMAINDER)

将在命令行中获取-a 之后的所有内容,并将其推入a

python test.py -toe -a bar fi -fo -fum -s fee -foo
usage: test.py [-h] [-s S] [-a ...]
test.py: error: unrecognized arguments: -toe

python test.py -a bar fi -fo -fum -s fee -foo
Namespace(a=[['bar', 'fi', '-fo', '-fum', '-s', 'fee', '-foo']], s=None)

请注意,即使 -s 是一个公认的参数,argparse.REMAINDER 也会将其添加到 -a 找到的参数列表中,因为它在命令行上位于 -a 之后

【讨论】:

    猜你喜欢
    • 2021-05-06
    • 2012-07-03
    • 2020-11-25
    • 2016-06-06
    • 2020-07-06
    • 2015-09-16
    • 2018-04-22
    • 2020-09-05
    • 1970-01-01
    相关资源
    最近更新 更多