无法让 argparse 读取带破折号的带引号的字符串? [英] Can't get argparse to read quoted string with dashes in it?
问题描述
有没有办法让 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, http://python.6.x6.nabble.com/issue9334-argparse-does-not-accept-options-taking-arguments-beginning-with-dash-regression-from-optp-td578790.html.它仅在 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 读取带破折号的带引号的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!