问题描述
我在写一个脚本,我想需要一个 - 价值与主机
开关,但如果 - 主机
开关没有指定我想解析失败的选项。
I'm writing a script and I want to require a --host
switch with value, but if the --host
switch isn't specified I want the option parsing to fail.
我似乎无法弄清楚如何做到这一点。该文档似乎只指定如何使参数值强制性的,不是交换机本身。
I can't seem to figure out how to do that. The docs seem to only specify how to make the argument value mandatory, not the switch itself.
推荐答案
我假设你正在使用optparse这里,虽然同样的技术将用于其他选项解析库工作。
I am assuming you are using optparse here, although the same technique will work for other option parsing libraries.
最简单的方法可能是使用所选的选项解析库来解析参数,然后引发OptionParser :: MissingArgument异常,如果主机的价值为零。
The simplest method is probably to parse the parameters using your chosen option parsing library and then raise an OptionParser::MissingArgument Exception if the value of host is nil.
以下code说明
#!/usr/bin/env ruby
require 'optparse'
options = {}
optparse = OptionParser.new do |opts|
opts.on('-h', '--host HOSTNAME', "Mandatory Host Name") do |f|
options[:host] = f
end
end
optparse.parse!
#Now raise an exception if we have not found a host option
raise OptionParser::MissingArgument if options[:host].nil?
puts "Host = #{options[:host]}"
与运行一个命令行这个例子
Running this example with a command line of
./program -h somehost
简单显示主机=,某
simple displays "Host = somehost"
尽管用缺失-h运行,没有文件名产生以下输出
Whilst running with a missing -h and no file name produces the following output
./program:15: missing argument: (OptionParser::MissingArgument)
和与./program -h命令行运行产生
And running with a command line of ./program -h produces
/usr/lib/ruby/1.8/optparse.rb:451:in `parse': missing argument: -h (OptionParser::MissingArgument)
from /usr/lib/ruby/1.8/optparse.rb:1288:in `parse_in_order'
from /usr/lib/ruby/1.8/optparse.rb:1247:in `catch'
from /usr/lib/ruby/1.8/optparse.rb:1247:in `parse_in_order'
from /usr/lib/ruby/1.8/optparse.rb:1241:in `order!'
from /usr/lib/ruby/1.8/optparse.rb:1332:in `permute!'
from /usr/lib/ruby/1.8/optparse.rb:1353:in `parse!'
from ./program:13
这篇关于如何指定所需的开关(未参数)使用Ruby OptionParser?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!