Argparse`append` 没有按预期工作 [英] Argparse `append` not working as expected

查看:32
本文介绍了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:错误:参数 -A/--module-args:需要一个参数

最小示例:

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天全站免登陆