解析 argv 时忽略无法识别的选项?
我正在编写一个脚本,充当插件类的 run
方法的代理。
该脚本将像这样调用:
> main.py -v --plugin=Foo --extra=bar -c
该命令的结果相当于:
plugin = my.module.Foo()
plugin.run(extra='bar', c=True)
请注意,--plugin
前面的任何内容都由 main.py 内部使用,不会传递给插件。 --plugin
之后的任何内容都会被 main.py 忽略,而是直接传递给插件。
我遇到的问题是我找不到类似 getopt
的类,它允许我解析 argv
而无需指定允许的选项列表。
我不想重写 getopt
并注释掉一行。还有更好的选择吗?
I'm writing a script that acts as a proxy for a plugin class's run
method.
The script would be invoked like this:
> main.py -v --plugin=Foo --extra=bar -c
The result of this command would be the equivalent of:
plugin = my.module.Foo()
plugin.run(extra='bar', c=True)
Note that anything in front of --plugin
is used internally by main.py and not passed to the plugin. Anything after --plugin
is ignored by main.py and instead passed directly to the plugin.
The problem I'm running into is that I can't find a getopt
-like class that will allow me to parse argv
without having to specify a list of allowed options.
I'd prefer not to have to rewrite getopt
with one line commented out. Are there any better options out there?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您想要的内容位于 argparse 库中,请参阅 http://docs.python.org/dev/library/argparse.html#partial-parsing:
What you want is in the
argparse
library, see http://docs.python.org/dev/library/argparse.html#partial-parsing:您可以做一些愚蠢的事情,只生成一个字典,您可以从中查找键等以确定如何处理每个项目......
You can do something silly and just generate a dictionary from which you can look up keys and the like to determine what to do with each item...
你很幸运。我编写了一个修改后的 getopt正是如此。然而,一个限制是空头期权必须先于多头期权。这可能是可以解决的。
You're in luck. I wrote a modified getopt that does exactly that. One limitition, however, is that short options must precede long options. That may be fixable.
我刚刚发现
getopt
如果遇到--
:请注意,上面的
argv
相当于调用:我特别喜欢这个解决方案,因为它为用户在订购方式上提供了一点额外的灵活性参数。
I just discovered that
getopt
will stop parsing if it encounters--
:Note that the above
argv
is the equivalent of calling:I like this solution particularly since it gives the user a little extra flexibility in how he wants to order the parameters.
使用正则表达式搜索
'plugin=
,如果找到,则分割该行并使用 getopt 解析每一半。Use a regular expression to search for
'plugin=
, and if found, split the line and use getopt to parse each half.