问题描述
是否有一种方法可以使argparse将两个引号之间的任何内容识别为单个参数?似乎不断看到破折号,并假设这是一个新选项的开始
Is there a way to make argparse recognize anything between two quotes as a single argument? It seems to keep seeing the dashes and assuming that it's the start of a new option
我有类似的东西:
mainparser = argparse.ArgumentParser()
subparsers = mainparser.add_subparsers(dest='subcommand')
parser = subparsers.add_parser('queue')
parser.add_argument('-env', '--extraEnvVars', type=str,
help='String of extra arguments to be passed to model.')
...other arguments added to parser...
但是当我跑步时:
python Application.py queue -env "-s WHATEVER -e COOL STUFF"
它给了我
Application.py queue: error: argument -env/--extraEnvVars: expected one argument
如果我不使用第一个破折号,那么它可以很好地工作,但是能够输入带有破折号的字符串是至关重要的.我尝试用\进行转义,这会导致它成功,但是会将\添加到参数字符串中.有人知道如何解决这个问题吗?无论-s是否是解析器中的参数,都会发生这种情况.
If I leave off the first dash, it works totally fine, but it's kind of crucial that I be able to pass in a string with dashes in it. I've tried escaping it with \ , which causes it to succeed but adds the \ to the argument string Does anyone know how to get around this? This happens whether or not -s is an argument in parser.
我正在使用Python 2.7.
I'm using Python 2.7.
python Application.py -env " -env"
工作正常,但是
python Application.py -env "-env"
没有.
看起来这实际上是一个已经在讨论中的错误: http://www.gossamer -threads.com/lists/python/bugs/89529 ,.仅在2.7中存在,而在optparse中不存在.
Looks like this is actually a bug that's being debated already: http://www.gossamer-threads.com/lists/python/bugs/89529, http://python.6.x6.nabble.com/issue9334-argparse-does-not-accept-options-taking-arguments-beginning-with-dash-regression-from-optp-td578790.html. It's only in 2.7 and not in optparse.
当前打开的错误报告为: http://bugs.python.org/issue9334
The current open bug report is: http://bugs.python.org/issue9334
推荐答案
您可以使用空格python tst.py -e ' -e blah'
来启动自变量,这是一个非常简单的解决方法.如果愿意,只需lstrip()
将其恢复正常的选项.
You can start the argument with a space python tst.py -e ' -e blah'
as a very simple workaround. Simply lstrip()
the option to put it back to normal, if you like.
或者,如果第一个子参数"也不是原始函数的有效参数,那么您根本不需要执行任何操作.也就是说,python tst.py -e '-s hi -e blah'
不起作用的唯一原因是因为-s
是tst.py
的有效选项.
Or, if the first "sub-argument" is not also a valid argument to the original function then you shouldn't need to do anything at all. That is, the only reason that python tst.py -e '-s hi -e blah'
doesn't work is because -s
is a valid option to tst.py
.
此外,现已弃用的 optparse 模块可以正常使用.
Also, the optparse module, now deprecated, works without any issue.
这篇关于无法使argparse读取带破折号的带引号的字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!