OptionParser - 支持命令行末尾的任何选项
我正在编写一个小程序,该程序应该在远程服务器上执行命令(假设有一个围绕 ssh [主机名] [命令] 的相当愚蠢的包装器)。
我想这样执行它:
./floep [command]
但是,我需要时不时地传递某些命令行:
./floep -v [command]
所以我决定为此使用 optparse.OptionParser 。 问题是,我有时命令也有参数,如果我这样做的话,它工作得很好:
./floep -v "uname -a"
但我也希望它在我使用时工作:
./floep -v uname -a
这个想法是,一旦我遇到第一个非选项参数,之后的所有内容都应该成为我指挥的一部分。
然而,这给了我:
Usage: floep [options] floep: error: no such option: -a
OptionParser 支持这种语法吗? 如果是这样:怎么办? 如果不是:解决这个问题的最佳方法是什么?
I'm writing a small program that's supposed to execute a command on a remote server (let's say a reasonably dumb wrapper around ssh [hostname] [command]
).
I want to execute it as such:
./floep [command]
However, I need to pass certain command lines from time to time:
./floep -v [command]
so I decided to use optparse.OptionParser for this. Problem is, I sometimes the command also has argument, which works fine if I do:
./floep -v "uname -a"
But I also want it to work when I use:
./floep -v uname -a
The idea is, as soon as I come across the first non-option argument, everything after that should be part of my command.
This, however, gives me:
Usage: floep [options] floep: error: no such option: -a
Does OptionParser support this syntax? If so: how?
If not: what's the best way to fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使用
disable_interspersed_args()
运行时:
Try using
disable_interspersed_args()
When run:
OptionParser 实例实际上可以在复杂情况的解析操作期间进行操作。 然而,在这种情况下,我相信您描述的场景是开箱即用的(如果属实的话,这将是个好消息!这种情况发生的频率如何?)。 请参阅文档中的此部分: 查询和操作你的选项解析器。
引用上面的链接:
OptionParser instances can actually be manipulated during the parsing operation for complex cases. In this case, however, I believe the scenario you describe is supported out-of-the-box (which would be good news if true! how often does that happen??). See this section in the docs: Querying and manipulating your option parser.
To quote the link above:
您可以使用如下所示的 bash 脚本:
${@} 为您提供未被 Shift 调用消耗的命令行的其余部分。
要使用 ssh,您只需将行从
${@}
到
ssh ${用户}@${主机} ${@}
test.sh echo bla
bla
test.sh -v echo bla
-v
bla
test.sh -v -s echo bla
-v
-s
布拉
You can use a bash script like this:
The ${@} gives you the rest of the command line that was not consumed by the shift calls.
To use ssh you simply change the line from
${@}
to
ssh ${user}@${host} ${@}
test.sh echo bla
bla
test.sh -v echo bla
-v
bla
test.sh -v -s echo bla
-v
-s
bla