Argparse `append` not working as expected [duplicate]

佐手、 提交于 2019-12-24 18:13:23

问题


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

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.

Here is my argument entry:

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

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

Minimal example:

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())

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.


回答1:


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"

Given the following 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)

...that usage returns:

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

whereas leaving off the leading spaces reproduces your error.



来源:https://stackoverflow.com/questions/45150153/argparse-append-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!