2009-10-09 46 views
42

我正在寫一個腳本,我想要一個帶有值的--host開關,但是如果沒有指定--host開關,我希望選項解析失敗。如何用Ruby OptionParser指定所需的開關(不是參數)?

我似乎無法弄清楚如何做到這一點。該文檔似乎只指定了如何使參數值爲強制性的,而不是開關本身。

+1

您需要更詳細地說明,舉個例子.... – khelll 2009-10-09 03:09:47

回答

56

我假設你在這裏使用optparse,雖然相同的技術將適用於其他選項解析庫。

最簡單的方法可能是使用您選擇的選項解析庫解析參數,然後在host的值爲nil時引發OptionParser :: MissingArgument異常。

下面的代碼說明

#!/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 

簡單顯示器的命令行本實施例中的 「主機=,某」

雖然與運行一個丟失-h和無文件名產生以下輸出

./program:15: missing argument: (OptionParser::MissingArgument) 

並與./program的命令行-h產生

/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 
+15

太臭這不是圖書館的一項內置功能 - 這不是很乾如果你有幾個需要的開關。謝謝。 – 2009-10-09 11:52:39

+4

我不想提出一個神祕的異常,而是傾向於通過調用'Kernel.abort'以非零狀態退出。它需要一個可選參數,您可以使用它來指定中止的原因。 – 2009-12-13 23:22:09

+4

同意泰德。它根本不是DRY,應該感到羞恥,因爲它不是。我的第一個命令行應用程序,我需要一個強制性的開關,所以這是不合情理的,這不包括在內。 – 2010-10-28 00:42:39

82

使用optparse上缺少交換機提供友好的輸出的一種方法運行:

#!/usr/bin/env ruby 
require 'optparse' 

options = {} 

optparse = OptionParser.new do |opts| 
    opts.on('-f', '--from SENDER', 'username of sender') do |sender| 
    options[:from] = sender 
    end 

    opts.on('-t', '--to RECIPIENTS', 'comma separated list of recipients') do |recipients| 
    options[:to] = recipients 
    end 

    options[:number_of_files] = 1 
    opts.on('-n', '--num_files NUMBER', Integer, "number of files to send (default #{options[:number_of_files]})") do |number_of_files| 
    options[:number_of_files] = number_of_files 
    end 

    opts.on('-h', '--help', 'Display this screen') do 
    puts opts 
    exit 
    end 
end 

begin 
    optparse.parse! 
    mandatory = [:from, :to]           # Enforce the presence of 
    missing = mandatory.select{ |param| options[param].nil? }  # the -t and -f switches 
    unless missing.empty?           # 
    raise OptionParser::MissingArgument.new(missing.join(', ')) # 
    end                # 
rescue OptionParser::InvalidOption, OptionParser::MissingArgument  # 
    puts $!.to_s               # Friendly output when parsing fails 
    puts optparse               # 
    exit                 # 
end                  # 

puts "Performing task with options: #{options.inspect}" 

運行而不-t-f切換顯示以下輸出:

Missing options: from, to 
Usage: test_script [options] 
    -f, --from SENDER    username of sender 
    -t, --to RECIPIENTS    comma separated list of recipients 
    -n, --num_files NUMBER   number of files to send (default 1) 
    -h, --help 

在a中運行分析方法begin/rescue子句允許對其他故障(例如缺少參數或無效開關值)進行友好格式化,例如,嘗試爲-n開關傳遞一個字符串。

+0

根據neilfws的意見修復 – volund 2010-02-04 22:03:20

+1

這並不壞,但它仍然不是很乾燥。你必須在那裏做很多工作,並且必須在兩個地方指定你的交換機。看看我的修補程序,這是更簡單,更乾燥。另外在我的博客:http://picklepumpers.com/wordpress/?p=949 – 2010-10-28 08:42:28

+0

這是一個很好的答案,謝謝volund。 – 2012-06-08 17:03:07

1

來自未知(谷歌)的答案很好,但包含一個小錯誤。

rescue OptionParser::InvalidArgument, OptionParser::MissingArgument 

應該

OptionParser::InvalidOption, OptionParser::MissingArgument 

否則,optparse.parse!將觸發OptionParser::InvalidOption標準錯誤輸出,而不是自定義消息。

9

我把它變成了一個寶石,你可以從rubygems下載和安裝。組織:

gem install pickled_optparse 

而且你可以檢出github上更新項目的源代碼:
http://github.com/PicklePumpers/pickled_optparse

- 較早的帖子信息 -

這是真的,真的纏着我,所以我固定它保持使用超級乾燥。

爲了讓剛加入所需的開關:選項數組中所需的符號的任何地方,像這樣:

opts.on("-f", "--foo [Bar]", String, :required, "Some required option") do |option| 
    @options[:foo] = option 
end 

然後在你的OptionParser塊的末尾添加這些中的一個打印出遺漏開關和使用說明:

if opts.missing_switches? 
    puts opts.missing_switches 
    puts opts 
    exit 
end 

終於使這一切工作,你需要下面的「optparse_required_switches.rb」文件某處添加到您的項目,並要求它,當你做你的命令行解析。

我寫了一個小文章上我的博客爲例: http://picklepumpers.com/wordpress/?p=949

下面是它的使用方法的一個例子修改OptionParser文件:

required_switches_example.rb

#!/usr/bin/env ruby 
require 'optparse' 
require_relative 'optparse_required_switches' 

# Configure options based on command line options 
@options = {} 
OptionParser.new do |opts| 
    opts.banner = "Usage: test [options] in_file[.srt] out_file[.srt]" 

    # Note that :required can be anywhere in the parameters 

    # Also note that OptionParser is bugged and will only check 
    # for required parameters on the last option, not my bug. 

    # required switch, required parameter 
    opts.on("-s Short", String, :required, "a required switch with just a short") do |operation| 
    @options[:operation] = operation 
    end 

    # required switch, optional parameter 
    opts.on(:required, "--long [Long]", String, "a required switch with just a long") do |operation| 
    @options[:operation] = operation 
    end 

    # required switch, required parameter 
    opts.on("-b", "--both ShortAndLong", String, "a required switch with short and long", :required) do |operation| 
    @options[:operation] = operation 
    end 

    # optional switch, optional parameter 
    opts.on("-o", "--optional [Whatever]", String, "an optional switch with short and long") do |operation| 
    @options[:operation] = operation 
    end 

    # Now we can see if there are any missing required 
    # switches so we can alert the user to what they 
    # missed and how to use the program properly. 
    if opts.missing_switches? 
    puts opts.missing_switches 
    puts opts 
    exit 
    end 

end.parse! 

optparse_required_switches.rb

# Add required switches to OptionParser 
class OptionParser 

    # An array of messages describing the missing required switches 
    attr_reader :missing_switches 

    # Convenience method to test if we're missing any required switches 
    def missing_switches? 
    [email protected]_switches.nil? 
    end 

    def make_switch(opts, block = nil) 
    short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], [] 
    ldesc, sdesc, desc, arg = [], [], [] 
    default_style = Switch::NoArgument 
    default_pattern = nil 
    klass = nil 
    n, q, a = nil 

    # Check for required switches 
    required = opts.delete(:required) 

    opts.each do |o| 

     # argument class 
     next if search(:atype, o) do |pat, c| 
     klass = notwice(o, klass, 'type') 
     if not_style and not_style != Switch::NoArgument 
      not_pattern, not_conv = pat, c 
     else 
      default_pattern, conv = pat, c 
     end 
     end 

     # directly specified pattern(any object possible to match) 
     if (!(String === o || Symbol === o)) and o.respond_to?(:match) 
     pattern = notwice(o, pattern, 'pattern') 
     if pattern.respond_to?(:convert) 
      conv = pattern.method(:convert).to_proc 
     else 
      conv = SPLAT_PROC 
     end 
     next 
     end 

     # anything others 
     case o 
     when Proc, Method 
      block = notwice(o, block, 'block') 
     when Array, Hash 
      case pattern 
      when CompletingHash 
      when nil 
       pattern = CompletingHash.new 
       conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert) 
      else 
       raise ArgumentError, "argument pattern given twice" 
      end 
      o.each {|pat, *v| pattern[pat] = v.fetch(0) {pat}} 
     when Module 
      raise ArgumentError, "unsupported argument type: #{o}", ParseError.filter_backtrace(caller(4)) 
     when *ArgumentStyle.keys 
      style = notwice(ArgumentStyle[o], style, 'style') 
     when /^--no-([^\[\]=\s]*)(.+)?/ 
      q, a = $1, $2 
      o = notwice(a ? Object : TrueClass, klass, 'type') 
      not_pattern, not_conv = search(:atype, o) unless not_style 
      not_style = (not_style || default_style).guess(arg = a) if a 
      default_style = Switch::NoArgument 
      default_pattern, conv = search(:atype, FalseClass) unless default_pattern 
      ldesc << "--no-#{q}" 
      long << 'no-' + (q = q.downcase) 
      nolong << q 
     when /^--\[no-\]([^\[\]=\s]*)(.+)?/ 
      q, a = $1, $2 
      o = notwice(a ? Object : TrueClass, klass, 'type') 
      if a 
      default_style = default_style.guess(arg = a) 
      default_pattern, conv = search(:atype, o) unless default_pattern 
      end 
      ldesc << "--[no-]#{q}" 
      long << (o = q.downcase) 
      not_pattern, not_conv = search(:atype, FalseClass) unless not_style 
      not_style = Switch::NoArgument 
      nolong << 'no-' + o 
     when /^--([^\[\]=\s]*)(.+)?/ 
      q, a = $1, $2 
      if a 
      o = notwice(NilClass, klass, 'type') 
      default_style = default_style.guess(arg = a) 
      default_pattern, conv = search(:atype, o) unless default_pattern 
      end 
      ldesc << "--#{q}" 
      long << (o = q.downcase) 
     when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/ 
      q, a = $1, $2 
      o = notwice(Object, klass, 'type') 
      if a 
      default_style = default_style.guess(arg = a) 
      default_pattern, conv = search(:atype, o) unless default_pattern 
      end 
      sdesc << "-#{q}" 
      short << Regexp.new(q) 
     when /^-(.)(.+)?/ 
      q, a = $1, $2 
      if a 
      o = notwice(NilClass, klass, 'type') 
      default_style = default_style.guess(arg = a) 
      default_pattern, conv = search(:atype, o) unless default_pattern 
      end 
      sdesc << "-#{q}" 
      short << q 
     when /^=/ 
      style = notwice(default_style.guess(arg = o), style, 'style') 
      default_pattern, conv = search(:atype, Object) unless default_pattern 
     else 
      desc.push(o) 
     end 

    end 

    default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern 
    if !(short.empty? and long.empty?) 
     s = (style || default_style).new(pattern || default_pattern, conv, sdesc, ldesc, arg, desc, block) 
    elsif !block 
     if style or pattern 
     raise ArgumentError, "no switch given", ParseError.filter_backtrace(caller) 
     end 
     s = desc 
    else 
     short << pattern 
     s = (style || default_style).new(pattern, conv, nil, nil, arg, desc, block) 
    end 

    # Make sure required switches are given 
    if required && !(default_argv.include?("-#{short[0]}") || default_argv.include?("--#{long[0]}")) 
     @missing_switches ||= [] # Should be placed in initialize if incorporated into Ruby proper 

     # This is more clear but ugly and long. 
     #missing = "-#{short[0]}" if !short.empty? 
     #missing = "#{missing} or " if !short.empty? && !long.empty? 
     #missing = "#{missing}--#{long[0]}" if !long.empty? 

     # This is less clear and uglier but shorter. 
     missing = "#{"-#{short[0]}" if !short.empty?}#{" or " if !short.empty? && !long.empty?}#{"--#{long[0]}" if !long.empty?}" 

     @missing_switches << "Missing switch: #{missing}" 
    end 

    return s, short, long, 
     (not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style), 
     nolong 
    end 

end 
+1

'pickled_optparse需要Ruby版本〜> 1.9.2.' :( – Nowaker 2011-09-24 16:04:17

+0

@DamianNowak - 克隆github repo並修改pickled_optparse.gemspec文件的第36行,然後執行'gem build。\ pickled_optparse.gemspec && gem install。\ pickled_optparse -0.1.1.gem',你很好去。 – Pakman 2013-09-20 16:10:38

3

如果需要主機,那麼可以肯定它不是一個選項,這是一個參數

考慮到這一點,以下是解決問題的方法。您可以詢問ARGV陣列以查看是否指定了主機,如果尚未指定,請致電abort("You must specify a host!")或類似的程序,以使您的程序退出並顯示錯誤狀態。

2

如果你做這樣的事情:

opts.on('-h', '--host', 
      'required host name [STRING]') do |h| 
    someoptions[:host] = h || nil 
    end 

然後someoptions[:host]要麼是從命令行或nil值(如果你不經過--host提供--host和/或沒有價值),你可以解析後輕鬆地測試它(和有條件失敗):

fail "Hostname not provided" unless someoptions[:host] 
4

我想出了用凝聚了您的貢獻清晰,簡潔的解決方案。它引發了一個OptionParser::MissingArgument異常,將缺少的參數作爲消息。該例外在rescue區塊中被捕獲,其餘例外來自OptionParser

#!/usr/bin/env ruby 
require 'optparse' 

options = {} 

optparse = OptionParser.new do |opts| 
    opts.on('-h', '--host hostname', "Host name") do |host| 
    options[:host] = host 
    end 
end 

begin 
    optparse.parse! 
    mandatory = [:host] 
    missing = mandatory.select{ |param| options[param].nil? } 
    raise OptionParser::MissingArgument, missing.join(', ') unless missing.empty? 
rescue OptionParser::ParseError => e 
    puts e 
    puts optparse 
    exit 
end 

運行這個例子:

 ./program    
missing argument: host 
Usage: program [options] 
    -h, --host hostname    Host name 
0

的想法是定義一個OptionParser,然後parse!它,puts,如果某些字段丟失。將filename設置爲空字符串默認情況下可能不是最好的方式,但你有想法。

require 'optparse' 

filename = '' 
options = OptionParser.new do |opts| 
    opts.banner = "Usage: swift-code-style.rb [options]" 

    opts.on("-iNAME", "--input-filename=NAME", "Input filename") do |name| 
     filename = name 
    end 
    opts.on("-h", "--help", "Prints this help") do 
     puts opts 
     exit 
    end 
end 

options.parse! 

if filename == '' 
    puts "Missing filename.\n---\n" 
    puts options 
    exit 
end 

puts "Processing '#{filename}'..." 

如果-i filename丟失,它會顯示:

~/prj/gem/swift-code-kit ./swift-code-style.rb 
Missing filename. 
--- 
Usage: swift-code-style.rb [options] 
    -i, --input-filename=NAME  Input filename 
    -h, --help      Prints this help 
相關問題