Argparse `append` 没有按预期工作

Argparse `append` not working as expected

我正在尝试配置 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 应该将这些东西放入列表时它期望一个参数。

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

作为一种粗略的解决方法,您可以在前缀 space:

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)

...那个用法 returns:

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

而离开领先的 spaces 会重现您的错误。