我遇到了 OptionParser 的问题make_switch
。
我的代码解析三个参数并运行测试以查看我的 MANDATORY 参数是否在这里:
#!/usr/bin/env ruby
require 'optparse'
require 'ostruct'
options = OpenStruct.new
@argv = ARGV
optparse = OptionParser.new do |opts|
@opts=opts
usage = "USAGE: ./#{File.basename($0)} [-v] -p xxxxxx"
@opts.banner = usage
@opts.on( '-p', '--pdu [PDU]', 'Specify a PDU to configure') do |res|
options.pdu = true
$pdu_name = res
end
@opts.on( '-v', '--[no-]verbose', 'Run verbosely') do
options.verbose = true
end
@opts.on( '-?', '-help','Show this message') do
puts "Help Me!"
puts @opts
exit 1
end
end
begin
if not @argv.empty?
optparse.order!(@argv)
if !options.pdu
$stderr.puts "Options -p missing."
$stderr.puts "#{@opts}\n\n"
exit 1
end
else
$stderr.puts "ERROR: Arguments Required."
$stderr.puts "#{@opts}\n\n"
exit 1
end
rescue OptionParser::InvalidOption
$stderr.puts "ERROR: Invalid option."
$stderr.puts "#{@opts}\n\n"
exit 1
end
一切正常,除了-?
:
xxx$ ./myscript.rb -?
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/optparse.rb:451:in
`parse': missing argument: -? (OptionParser::MissingArgument)
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/optparse.rb:1295:in `parse_in_order'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/optparse.rb:1254:in `catch'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/optparse.rb:1254:in `parse_in_order'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/optparse.rb:1248:in `order!'
blabla
然而-help
完美地工作:
xxxx$ ./myscript.rb -help
Help me!
USAGE: ./myscript.rb [-v] -p xxxxxx
-p, --pdu [PDU] Specify a PDU to configure
-v, --[no-]verbose Run verbosely
-?, -help Show this message
更令人惊讶的是,-? -v
它也有效:
xxxx$ ./myscript.rb -? -v
Help Me!
USAGE: ./myscript.rb [-v] -p xxxxxx
-p, --pdu [PDU] Specify a PDU to configure
-v, --[no-]verbose Run verbosely
-?, -help Show this message
我做错了什么?
如果我在代码中替换-?
为,也会出现同样的问题。-h