有了:
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
的参数。
没有引号,-f
是单独的并且被解释为标志。
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
或一些其他OS /外壳,不处理引号以同样的方式?
在Argparse `append` not working as expected
你一个稍微不同的命令行问:
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
通过为一个字符串传递。由于空间的原因,不会将其解释为标志。但它确实将这个光秃秃的'-t'解释为一面旗帜。
关于将未定义的'-xxx'字符串解释为参数而不是标记的可能性有一个错误/问题。我不得不看看是否有任何东西进入生产。
有关如何将字符串分类为标志或参数的详细信息,请参见argparse.ArgumentParser._parse_optional
方法。它包含注释:
# if it contains a space, it was meant to be a positional
if ' ' in arg_string:
return None
http://bugs.python.org/issue9334argparse does not accept options taking arguments beginning with dash (regression from optparse)
是对话题的老长的bug /问题。
看看'sys.argv'。引号是通过解析器还是被shell所吞噬? – hpaulj