配置argparse以接受带引号的参数 [英] Configure argparse to accept quoted arguments

查看:232
本文介绍了配置argparse以接受带引号的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,除其他外,该程序允许用户通过参数指定要加载的模块(然后用于执行动作).我正在尝试建立一种将参数轻松传递到此内部模块的方法,并且尝试使用ArgParse的action='append'使其建立一个参数列表,然后将其传递给我.

I am writing a program which, among other things, allows the user to specify through an argument a module to load (and then use to perform actions). I am trying to set up a way to easily pass arguments through to this inner module, and I was attempting to use ArgParse's action='append' to have it build a list of arguments that I would then pass through.

这是我正在使用的参数的基本布局

Here is a basic layout of the arguments that I am using

parser.add_argument('-M', '--module',
                    help="Module to run on changed files - should be in format MODULE:CLASS\n\
                          Specified class must have function with the signature run(src, dest)\
                          and return 0 upon success",
                    required=True)
parser.add_argument('-A', '--module_args',
                    help="Arg to be passed through to the specified module",
                    action='append',
                    default=[])

但是-如果我随后尝试使用python my_program -M module:class -A "-f filename"运行该程序(我想将-f filename传递到我的模块中),它似乎正在将-f解析为其自己的参数(并且我得到了错误my_program: error: argument -A/--module_args: expected one argument

However - if I then try to run this program with python my_program -M module:class -A "-f filename" (where I would like to pass through the -f filename to my module) it seems to be parsing the -f as its own argument (and I get the error my_program: error: argument -A/--module_args: expected one argument

有什么想法吗?

推荐答案

使用:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-M', '--module',
                    help="Module to run on changed files - should be in format MODULE:CLASS\n\
                          Specified class must have function with the signature run(src, dest)\
                          and return 0 upon success",
                    )
parser.add_argument('-A', '--module_args',
                    help="Arg to be passed through to the specified module",
                    action='append',
                    default=[])
import sys
print(sys.argv)
print(parser.parse_args())

我得到:

1028:~/mypy$ python stack45146728.py -M module:class -A "-f filename"
['stack45146728.py', '-M', 'module:class', '-A', '-f filename']
Namespace(module='module:class', module_args=['-f filename'])

这使用的是Linux shell.如sys.argv所示,带引号的字符串仍然是一个字符串,并且可以正确地解释为-A的参数.

This is using a linux shell. The quoted string remains one string, as seen in the sys.argv, and is properly interpreted as an argument to -A.

-f不带引号,并且被解释为标志.

Without the quotes the -f is separate and interpreted as a flag.

1028:~/mypy$ python stack45146728.py -M module:class -A -f filename
['stack45146728.py', '-M', 'module:class', '-A', '-f', 'filename']
usage: stack45146728.py [-h] [-M MODULE] [-A MODULE_ARGS]
stack45146728.py: error: argument -A/--module_args: expected one argument

您是否使用windows或其他无法处理引号的操作系统/外壳?

Are you using windows or some other OS/shell that doesn't handle quotes the same way?

Argparse`append`不能按预期工作

您询问的命令行略有不同:

you asked about a slightly different command line:

1032:~/mypy$ python stack45146728.py  -A "-k filepath" -A "-t"
['stack45146728.py', '-A', '-k filepath', '-A', '-t']
usage: stack45146728.py [-h] [-M MODULE] [-A MODULE_ARGS]
stack45146728.py: error: argument -A/--module_args: expected one argument

正如我已经提到的,-k filepath作为一个字符串传递.由于篇幅所限,argparse不会将其解释为标志.但是它确实将裸露的"-t"解释为标志.

As I already noted -k filepath is passed through as one string. Because of the space, argparse does not interpret that as a flag. But it does interpret the bare '-t' as a flag.

存在一个错误/问题,涉及将未定义的"-xxx"字符串解释为参数而不是标志的可能性.我必须抬头看看是否有任何东西可以投入生产.

There was a bug/issue about the possibility of interpreting undefined '-xxx' strings as arguments instead of flags. I'd have to look that up to see whether anything made it into to production.

有关如何将字符串归类为标志或参数的详细信息,可以在argparse.ArgumentParser._parse_optional方法中找到.它包含一个注释:

Details of how strings are categorized as flag or argument can be found in argparse.ArgumentParser._parse_optional method. It contains a comment:

    # if it contains a space, it was meant to be a positional
    if ' ' in arg_string:
        return None

http://bugs.python.org/issue9334 argparse does not accept options taking arguments beginning with dash (regression from optparse)年代久远该主题的错误/问题.

http://bugs.python.org/issue9334 argparse does not accept options taking arguments beginning with dash (regression from optparse) is an old and long bug/issue on the topic.

这篇关于配置argparse以接受带引号的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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