Argparse`addnd`没有按预期工作

时间:2017-07-17 17:21:26

标签: python arguments argparse

我正在尝试配置argparse以允许我指定将在未来传递到另一个模块的参数。我想要的功能允许我插入诸如-A "-f filepath" -A "-t"之类的参数并生成['-f filepath', '-t']之类的列表。

在文档中,添加action='append'似乎应该这样做 - 但是在尝试多次指定-A参数时出现错误。

这是我的参数条目:

parser.add_argument('-A', '--module-args',
                    help="Arg to be passed through to the specified module",
                    action='append')

运行python my_program.py -A "-k filepath" -A "-t"会从argparse:

产生此错误

my_program.py: error: argument -A/--module-args: expected one argument

最小例子:

from mdconf import ArgumentParser
import sys

def parse_args():
    parser = ArgumentParser()
    parser.add_argument('-A', '--module-args',
                        help="Arg to be passed through to the module",
                        action='append')
    return parser.parse_args()

def main(args=None):
    try:
        args = parse_args()
    except Exception as ex:
        print("Exception: {}".format(ex))
        return 1
    print(args)
    return 0

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

有什么想法吗?我觉得奇怪的是,当append将这些东西放入列表时,它告诉我它需要一个参数。

1 个答案:

答案 0 :(得分:0)

问题不在于-A不允许多次调用。这是-t被视为一个单独的选项,而不是-A选项的参数。

作为粗略的解决方法,您可以为空格添加前缀:

python my_program.py \
  -A " -k filepath" \
  -A " -t"

鉴于以下Minimal, Complete and Verifiable Example

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-A', '--module-args',
                    help="Arg to be passed through to the specified module",
                    action='append')
args = parser.parse_args()
print repr(args.module_args)

......该用法返回:

[' -k filepath', ' -t']

而忽略前导空格会重现您的错误。

相关问题