OptionParse没有参数时显示横幅。

22

我正在使用Ruby的OptionParser

在其他语言如C、Python等中,也有类似的命令行参数解析器,它们通常提供一种在未提供参数或参数错误时显示帮助信息的方式。

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: calc.rb [options]"

  opts.on("-l", "--length L", Integer, "Length") { |l| options[:length] = l }
  opts.on("-w", "--width W", Integer, "Width") { |w| options[:width] = w }

  opts.on_tail("-h", "--help", "Show this message") do
    puts opts
    exit
  end
end.parse!

问题:

  1. 是否有一种方法可以默认显示帮助消息,如果没有传递参数(ruby calc.rb)?
  2. 如果必需参数未给出或无效怎么办?假设length是必需的参数,用户没有传递它或传递了类似于-l FOO这样错误的内容怎么办?

7
在解析之前添加这行代码:ARGV.push('-h') if ARGV.empty? - Малъ Скрылевъ
@МалъСкрылевъ,是的,谢谢! - Israel
我的回答有帮助吗?=) - Малъ Скрылевъ
3个回答

47

ARGV为空时,只需将-h键添加到中,以便您可以执行类似于以下内容的操作:

require 'optparse'

ARGV << '-h' if ARGV.empty?

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: calc.rb [options]"

  opts.on("-l", "--length L", Integer, "Length") { |l| options[:length] = l }
  opts.on("-w", "--width W", Integer, "Width") { |w| options[:width] = w }

  opts.on_tail("-h", "--help", "Show this message") do
    puts opts
    exit
  end
end.parse!

0

我的脚本需要精确的2个参数,所以我在解析后使用了这段代码来检查ARGV.length

if ARGV.length != 2 then
  puts optparse.help
  exit 1
end

-1
你可以在解析之前检查 ARGV(如上面的答案):
ARGV << '-h' if ARGV.empty? 或者在解析后检查选项哈希表:
if @options.empty?
  puts optparse.help
  puts 'At least 1 argument should be supplied!'
end
这是我使用 OptionParse 确保必需参数的方法(找不到任何内置功能):
begin
  optparse.parse!
  mandatory = [:length, :width]                                         # 强制存在
  missing = mandatory.select{ |param| @options[param].nil? }            # 必需开关::length, :width
  if not missing.empty?                                                 #
        puts "Missing options: #{missing.join(', ')}"                   #
        puts optparse.help                                              #
        exit 2                                                          #
  end                                                                   #
rescue OptionParser::InvalidOption, OptionParser::MissingArgument => error     #
  puts error                                                                   # 解析失败时友好输出
  puts optparse                                                                #
  exit 2                                                                       #
end     

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接