您如何使用 Ruby OptionParser 指定所需的开关(不是参数)? [英] How do you specify a required switch (not argument) with Ruby OptionParser?

查看:23
本文介绍了您如何使用 Ruby OptionParser 指定所需的开关(不是参数)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本,我想要一个带有值的 --host 开关,但是如果没有指定 --host 开关,我想要选项解析失败.

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.

最简单的方法可能是使用您选择的选项解析库解析参数,然后在主机的值为 nil 时引发 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.

以下代码说明

#!/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]}"

使用

./program -h somehost

简单显示Host = 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 指定所需的开关(不是参数)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆