【问题标题】:Force mandatory command line argument using OptionParse in Ruby在 Ruby 中使用 OptionParse 强制强制命令行参数
【发布时间】:2013-09-30 07:58:27
【问题描述】:

我有这个代码:

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

  opts.on("-g", "--grade [N]", "Grade") do |g|
    options[:grade] = g
  end

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

end
opt_parse.parse!

如何强制设置-g 参数?如果未指定,则触发 usage 消息,如调用 -h 参数时所示。

【问题讨论】:

    标签: ruby command-line-arguments optionparser


    【解决方案1】:

    OptionParser 没有检查强制选项的内置方法。但是解析后很容易检查:

    if options[:grade].nil?
      abort(opt_parse.help)
    end
    

    如果您不寻找任何过于复杂的东西,手动解析命令行相对容易:

    # Naive error checking
    abort('Usage: ' + $0 + ' site id ...') unless ARGV.length >= 2
    
    # First item (site) is mandatory
    site = ARGV.shift
    
    ARGV.each do | id |
      # Do something interesting with each of the ids
    end
    

    但是当您的选项开始变得更加复杂时,您可能需要使用选项解析器,例如 OptionParser:

    require 'optparse'
    
    # The actual options will be stored in this hash
    options = {}
    
    # Set up the options you are looking for
    optparse = OptionParser.new do |opts|
      opts.banner = "Usage: #{$0} -s NAME id ..."
    
      opts.on("-s", "--site NAME", "Site name") do |s|
        options[:site] = s
      end
    
      opts.on( '-h', '--help', 'Display this screen' ) do
        puts opts
        exit
      end
    end
    
    # The parse! method also removes any options it finds from ARGV.
    optparse.parse!
    

    还有一个非破坏性的parse,但如果您打算使用ARGV 中的其余部分,它的用处会小很多。

    OptionParser 类没有强制执行强制参数的方法(例如本例中的--site)。但是,您可以在运行parse! 后自行检查:

    # Slightly more sophisticated error checking
    if options[:site].nil? or ARGV.length == 0
      abort(optparse.help)
    end
    

    有关更通用的强制选项处理程序,请参阅this answer。如果不清楚,所有选项都是可选的,除非您竭尽全力将它们设为强制性。

    【讨论】: