[英]Command line option parsing in Ruby
我有一个ruby脚本,它可以如下解析提供给它的命令行选项:
#!/usr/bin/ruby
require 'optparse'
puts 'Hello World!, This is my first ruby program'
options = {}
optparse = OptionParser.new do|opts|
opts.banner = "Featbuild minimal trial script for command line parsing"
options[:cpl] = nil
opts.on('-cpl SWITCH_STATE', 'compile on or off') do|cplopt|
options[:cpl] = cplopt
OPT_CPL=cplopt
puts cplopt
end
opts.on('-h', '--help', 'Display this screen') do
puts opts
exit
end
end
optparse.parse!
output = open("mypipe", "w+")
output.puts OPT_CPL
#output.flush
现在,行opts.on('-cpl SWITCH_STATE', 'compile on or off') do|cplopt|
在上面的脚本中我遇到了问题。
我相信我们可以通过以下方式做到这一点:1.) opts.on('--cpl SWITCH_STATE', 'compile on or off') do|cplopt|
2.) opts.on('-c', '--cpl SWITCH_STATE', 'compile on or off') do|cplopt|
3.) opts.on('-cpl SWITCH_STATE', 'compile on or off') do|cplopt|
这是我通过的有效参数:
$./try1.rb --cpl on
$./try1.rb -c on
这不起作用:$。/ try1.rb -cpl on
Ruby而不是使用“ on”作为选项参数,而是使用“ pl”,就像指定了$./try.rb -c pl
。
我想将字符串$./try1.rb -cpl on
解析为'on'
被传递给'cplopt'
opts.on()
方法的块。
我指的是本教程: http : //ruby.about.com/od/advancedruby/a/optionparser2.htm
似乎在Ruby中不可能'-cpl on'
吗? 是这样吗
我可以在这里应用其他哪些替代解决方案?
尝试使用Trollop ,因为它可以使选项解析更加轻松。
require 'trollop'
opts = Trollop::options do
version "compile 0.1.0"
banner "Usage: compile <option> - where [options] are:"
opt :cpl, "compile on or off", :type => :string, :default => "off"
end
puts opts.cpl
运行时会导致:
$ ruby ./trollop.rb --cpl on
on
$ ruby ./trollop.rb --cpl off
off
$ ruby ./trollop.rb -c on
on
$ ruby ./trollop.rb -c off
off
$ ruby ./trollop.rb
off
Trollop 2.0支持no-
布尔选项否定它你会发现比处理更容易on/off
的字符串。
opt "cpl", "Compile", :default => true
运行时会导致:
$ ruby trollop.rb --cpl
true
$ ruby trollop.rb --no-cpl
false
我认为您需要确保单引号中仅包含cp1而不是
-cpl SWITCH_STATE
做
opts.on('-cpl', 'compile on or off') do|cplopt|
options[:cpl] = cplopt
OPT_CPL=cplopt
puts cplopt
end
这是一个例子:
opts.on('-s', '--size 1G or 1024M', '1G or 1024M') do |s|
options[:size] = s;
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.