Argparse`append`不能按预期工作 [英] Argparse `append` not working as expected

查看:99
本文介绍了Argparse`append`不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试配置argparse,以允许我指定将传递给后续模块的参数.我想要的功能允许我插入诸如-A "-f filepath" -A "-t"之类的参数并产生诸如['-f filepath', '-t']之类的列表.

I am trying to configure argparse to allow me to specify arguments that will be passed onto another module down the road. My desired functionality would allow me to insert arguments such as -A "-f filepath" -A "-t" and produce a list such as ['-f filepath', '-t'].

在文档中,似乎添加action='append'应该可以完全做到这一点-但是,当尝试多次指定-A参数时出现错误.

In the docs it seems that adding action='append' should do exactly this - however I am getting an error when attempting to specify the -A argument more than once.

这是我的论点条目:

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产生此错误:

Running python my_program.py -A "-k filepath" -A "-t" produces this error from 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应该将这些内容放入列表时需要一个参数.

Any ideas? I find it strange that it is telling me that it expects one argument when the append should be putting these things into a list.

推荐答案

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

The problem isn't that -A isn't allowed to be called more than once. It's that the -t is seen as a separate option, not an argument to the -A option.

作为一种粗略的解决方法,您可以在空格前加上前缀:

As a crude workaround, you can prefix a space:

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


给出以下最小,完整和可验证的示例:

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']

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

whereas leaving off the leading spaces reproduces your error.

这篇关于Argparse`append`不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆