class OptionParser
OptionParser
开始使用 OptionParser?
请参阅 教程。
简介
OptionParser 是一个用于命令行选项分析的类。它比 GetoptLong 更高级,也更容易使用,是更符合 Ruby 风格的解决方案。
特性
-
参数规范和处理它的代码写在同一个地方。
-
它可以输出选项摘要;您无需单独维护此字符串。
-
可选参数和必选参数的指定非常灵活。
-
参数可以自动转换为指定的类。
-
参数可以限制在某个集合内。
所有这些特性都在下面的示例中进行了演示。有关完整文档,请参阅 make_switch。
最小示例
require 'optparse' options = {} OptionParser.new do |parser| parser.banner = "Usage: example.rb [options]" parser.on("-v", "--[no-]verbose", "Run verbosely") do |v| options[:verbose] = v end end.parse! p options p ARGV
生成帮助信息
OptionParser 可用于自动生成您编写的命令的帮助信息。
require 'optparse' Options = Struct.new(:name) class Parser def self.parse(options) args = Options.new("world") opt_parser = OptionParser.new do |parser| parser.banner = "Usage: example.rb [options]" parser.on("-nNAME", "--name=NAME", "Name to say hello to") do |n| args.name = n end parser.on("-h", "--help", "Prints this help") do puts parser exit end end opt_parser.parse!(options) return args end end options = Parser.parse %w[--help] #=> # Usage: example.rb [options] # -n, --name=NAME Name to say hello to # -h, --help Prints this help
必需参数
对于需要参数的选项,选项规范字符串中可以包含一个全大写的选项名称。如果选项在使用时缺少必需的参数,将会引发异常。
require 'optparse' options = {} OptionParser.new do |parser| parser.on("-r", "--require LIBRARY", "Require the LIBRARY before executing your script") do |lib| puts "You required #{lib}!" end end.parse!
已使用
$ ruby optparse-test.rb -r optparse-test.rb:9:in '<main>': missing argument: -r (OptionParser::MissingArgument) $ ruby optparse-test.rb -r my-library You required my-library!
类型强制转换
OptionParser 支持将命令行参数强制转换为对象。
OptionParser 提供了一些现成的类型强制转换。它们是:
-
Date–Date.parse可接受的任何内容(需要require 'optparse/date') -
DateTime–DateTime.parse可接受的任何内容(需要require 'optparse/date') -
Time–Time.httpdate或Time.parse可接受的任何内容(需要require 'optparse/time') -
Shellwords–Shellwords.shellwords可接受的任何内容(需要require 'optparse/shellwords') -
String– 任何非空字符串 -
Integer– 任何整数。会转换八进制(例如:124, -3, 040)。 -
Float– 任何浮点数(例如:10, 3.14, -100E+13)。 -
Numeric– 任何整数、浮点数或有理数(1, 3.4, 1/3)。 -
DecimalInteger– 类似于Integer,但不接受八进制格式。 -
OctalInteger– 类似于Integer,但不接受十进制格式。 -
DecimalNumeric– 十进制整数或浮点数。 -
TrueClass– 接受 ‘+, yes, true, -, no, false’,默认值为true。 -
FalseClass– 与TrueClass相同,但默认值为false。 -
Array– 以 ‘,’ 分隔的字符串(例如:1,2,3)。 -
Regexp– 正则表达式。也包含选项。
我们还可以添加自定义的强制转换,稍后将介绍。
使用内置转换
例如,这里使用了内置的 Time 转换。其他内置转换的行为方式相同。OptionParser 将尝试将参数解析为 Time。如果成功,该时间将被传递给处理块。否则,将引发异常。
require 'optparse' require 'optparse/time' OptionParser.new do |parser| parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time| p time end end.parse!
已使用
$ ruby optparse-test.rb -t nonsense ... invalid argument: -t nonsense (OptionParser::InvalidArgument) $ ruby optparse-test.rb -t 10-11-12 2010-11-12 00:00:00 -0500 $ ruby optparse-test.rb -t 9:30 2014-08-13 09:30:00 -0400
创建自定义转换
可以使用 OptionParser 上的 accept 方法来创建转换器。它指定了每当指定某个类时应调用哪个转换块。下面的示例使用它在 on 处理程序接收到 User 对象之前获取该对象。
require 'optparse' User = Struct.new(:id, :name) def find_user id not_found = ->{ raise "No User Found for id #{id}" } [ User.new(1, "Sam"), User.new(2, "Gandalf") ].find(not_found) do |u| u.id == id end end op = OptionParser.new op.accept(User) do |user_id| find_user user_id.to_i end op.on("--user ID", User) do |user| puts user end op.parse!
已使用
$ ruby optparse-test.rb --user 1 #<struct User id=1, name="Sam"> $ ruby optparse-test.rb --user 2 #<struct User id=2, name="Gandalf"> $ ruby optparse-test.rb --user 3 optparse-test.rb:15:in 'block in find_user': No User Found for id 3 (RuntimeError)
将选项存储到 Hash 中
order、parse 等方法的 into 选项会将命令行选项存储到 Hash 中。
require 'optparse' options = {} OptionParser.new do |parser| parser.on('-a') parser.on('-b NUM', Integer) parser.on('-v', '--verbose') end.parse!(into: options) p options
已使用
$ ruby optparse-test.rb -a
{:a=>true}
$ ruby optparse-test.rb -a -v
{:a=>true, :verbose=>true}
$ ruby optparse-test.rb -a -b 100
{:a=>true, :b=>100}
完整示例
以下示例是一个完整的 Ruby 程序。您可以运行它,看看指定各种选项的效果。这可能是学习 optparse 特性的最佳方法。
require 'optparse' require 'optparse/time' require 'ostruct' require 'pp' class OptparseExample Version = '1.0.0' CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary] CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" } class ScriptOptions attr_accessor :library, :inplace, :encoding, :transfer_type, :verbose, :extension, :delay, :time, :record_separator, :list def initialize self.library = [] self.inplace = false self.encoding = "utf8" self.transfer_type = :auto self.verbose = false end def define_options(parser) parser.banner = "Usage: example.rb [options]" parser.separator "" parser.separator "Specific options:" # add additional options perform_inplace_option(parser) delay_execution_option(parser) execute_at_time_option(parser) specify_record_separator_option(parser) list_example_option(parser) specify_encoding_option(parser) optional_option_argument_with_keyword_completion_option(parser) boolean_verbose_option(parser) parser.separator "" parser.separator "Common options:" # No argument, shows at tail. This will print an options summary. # Try it and see! parser.on_tail("-h", "--help", "Show this message") do puts parser exit end # Another typical switch to print the version. parser.on_tail("--version", "Show version") do puts Version exit end end def perform_inplace_option(parser) # Specifies an optional option argument parser.on("-i", "--inplace [EXTENSION]", "Edit ARGV files in place", "(make backup if EXTENSION supplied)") do |ext| self.inplace = true self.extension = ext || '' self.extension.sub!(/\A\.?(?=.)/, ".") # Ensure extension begins with dot. end end def delay_execution_option(parser) # Cast 'delay' argument to a Float. parser.on("--delay N", Float, "Delay N seconds before executing") do |n| self.delay = n end end def execute_at_time_option(parser) # Cast 'time' argument to a Time object. parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time| self.time = time end end def specify_record_separator_option(parser) # Cast to octal integer. parser.on("-F", "--irs [OCTAL]", OptionParser::OctalInteger, "Specify record separator (default \\0)") do |rs| self.record_separator = rs end end def list_example_option(parser) # List of arguments. parser.on("--list x,y,z", Array, "Example 'list' of arguments") do |list| self.list = list end end def specify_encoding_option(parser) # Keyword completion. We are specifying a specific set of arguments (CODES # and CODE_ALIASES - notice the latter is a Hash), and the user may provide # the shortest unambiguous text. code_list = (CODE_ALIASES.keys + CODES).join(', ') parser.on("--code CODE", CODES, CODE_ALIASES, "Select encoding", "(#{code_list})") do |encoding| self.encoding = encoding end end def optional_option_argument_with_keyword_completion_option(parser) # Optional '--type' option argument with keyword completion. parser.on("--type [TYPE]", [:text, :binary, :auto], "Select transfer type (text, binary, auto)") do |t| self.transfer_type = t end end def boolean_verbose_option(parser) # Boolean switch. parser.on("-v", "--[no-]verbose", "Run verbosely") do |v| self.verbose = v end end end # # Return a structure describing the options. # def parse(args) # The options specified on the command line will be collected in # *options*. @options = ScriptOptions.new @args = OptionParser.new do |parser| @options.define_options(parser) parser.parse!(args) end @options end attr_reader :parser, :options end # class OptparseExample example = OptparseExample.new options = example.parse(ARGV) pp options # example.options pp ARGV
Shell Completion
对于现代 Shell(例如 bash、zsh 等),您可以使用 Shell 补全功能来完成命令行选项。
进一步的文档
上面的示例以及配套的 教程 应该足以让您学会如何使用这个类。如果您有任何问题,请在 bugs.ruby-lang.org 上提交一个 ticket。
Constants
属性
默认情况下要解析的字符串。
在错误消息和默认横幅中显示的程序名称,默认为 $0。
是否在遇到未知选项时引发异常。
发布代码
是否要求选项完全匹配(不允许将缩写的长选项用作短选项)。
在错误消息和默认横幅中显示的程序名称,默认为 $0。
摘要中选项列表部分的宽度。必须是 Numeric。
摘要中选项列表部分的宽度。必须是 Numeric。
Public Class Methods
Source
# File lib/optparse.rb, line 1237 def self.accept(*args, &blk) top.accept(*args, &blk) end
请参阅 accept。
Source
# File lib/optparse.rb, line 1939 def self.getopts(*args, symbolize_names: false) new.getopts(*args, symbolize_names: symbolize_names) end
请参阅 getopts。
Source
# File lib/optparse.rb, line 1159 def self.inc(arg, default = nil) case arg when Integer arg.nonzero? when nil default.to_i + 1 end end
根据 arg 返回 default 的递增值。
Source
# File lib/optparse.rb, line 1182 def initialize(banner = nil, width = 32, indent = ' ' * 4) @stack = [DefaultList, List.new, List.new] @program_name = nil @banner = banner @summary_width = width @summary_indent = indent @default_argv = ARGV @require_exact = false @raise_unknown = true add_officious yield self if block_given? end
初始化实例,如果使用块调用则会 yield 自身。
banner-
横幅消息。
width-
摘要宽度。
indent-
摘要缩进。
Source
# File lib/optparse.rb, line 1250 def self.reject(*args, &blk) top.reject(*args, &blk) end
请参阅 reject。
Source
# File lib/optparse/version.rb, line 10 def show_version(*pkgs) progname = ARGV.options.program_name result = false show = proc do |klass, cname, version| str = "#{progname}" unless klass == ::Object and cname == :VERSION version = version.join(".") if Array === version str << ": #{klass}" unless klass == Object str << " version #{version}" end [:Release, :RELEASE].find do |rel| if klass.const_defined?(rel) str << " (#{klass.const_get(rel)})" end end puts str result = true end if pkgs.size == 1 and pkgs[0] == "all" self.search_const(::Object, /\AV(?:ERSION|ersion)\z/) do |klass, cname, version| unless cname[1] == ?e and klass.const_defined?(:Version) show.call(klass, cname.intern, version) end end else pkgs.each do |pkg| begin pkg = pkg.split(/::|\//).inject(::Object) {|m, c| m.const_get(c)} v = case when pkg.const_defined?(:Version) pkg.const_get(n = :Version) when pkg.const_defined?(:VERSION) pkg.const_get(n = :VERSION) else n = nil "unknown" end show.call(pkg, n, v) rescue NameError end end end result end
如果定义了 Version,则显示包的版本字符串。
pkgs-
包列表
Source
# File lib/optparse.rb, line 1212 def self.terminate(arg = nil) throw :terminate, arg end
请参阅 terminate。
Source
# File lib/optparse.rb, line 1150 def self.with(*args, &block) opts = new(*args) opts.instance_eval(&block) opts end
Public Instance Methods
Source
# File lib/optparse.rb, line 1360 def abort(mesg = $!) super("#{program_name}: #{mesg}") end
Source
# File lib/optparse.rb, line 1233 def accept(*args, &blk) top.accept(*args, &blk) end
指定接受类 t。参数字符串将被传递给块,块应将其转换为所需的类。
t-
参数类说明符,可以是任何对象,包括 Class。
pat-
参数模式,默认为
t,如果它响应match。
accept(t, pat, &block)
Source
# File lib/optparse.rb, line 1987 def additional_message(typ, opt) return unless typ and opt and defined?(DidYouMean::SpellChecker) all_candidates = [] visit(:get_candidates, typ) do |candidates| all_candidates.concat(candidates) end all_candidates.select! {|cand| cand.is_a?(String) } checker = DidYouMean::SpellChecker.new(dictionary: all_candidates) DidYouMean.formatter.message_for(all_candidates & checker.correct(opt)) end
返回附加信息。
Source
# File lib/optparse.rb, line 2001 def candidate(word) list = [] case word when '-' long = short = true when /\A--/ word, arg = word.split(/=/, 2) argpat = Completion.regexp(arg, false) if arg and !arg.empty? long = true when /\A-/ short = true end pat = Completion.regexp(word, long) visit(:each_option) do |opt| next unless Switch === opt opts = (long ? opt.long : []) + (short ? opt.short : []) opts = Completion.candidate(word, true, pat, &opts.method(:each)).map(&:first) if pat if /\A=/ =~ opt.arg opts.map! {|sw| sw + "="} if arg and CompletingHash === opt.pattern if opts = opt.pattern.candidate(arg, false, argpat) opts.map!(&:last) end end end list.concat(opts) end list end
返回 word 的候选项。
Source
# File lib/optparse.rb, line 1631 def define(*opts, &block) top.append(*(sw = make_switch(opts, block))) sw[0] end
根据给定的参数 params 创建一个选项。请参阅 新选项的参数。
如果给出了块,则该块是创建选项的处理程序。当在命令行解析过程中遇到该选项时,将使用该选项的参数(如果存在)调用该块。请参阅 选项处理程序。
Source
# File lib/optparse/kwargs.rb, line 15 def define_by_keywords(options, method, **params) method.parameters.each do |type, name| case type when :key, :keyreq op, cl = *(type == :key ? %w"[ ]" : ["", ""]) define("--#{name}=#{op}#{name.upcase}#{cl}", *params[name]) do |o| options[name] = o end end end options end
Source
# File lib/optparse.rb, line 1652 def define_head(*opts, &block) top.prepend(*(sw = make_switch(opts, block))) sw[0] end
根据给定的参数 params 创建一个选项。请参阅 新选项的参数。
如果给出了块,则该块是创建选项的处理程序。当在命令行解析过程中遇到该选项时,将使用该选项的参数(如果存在)调用该块。请参阅 选项处理程序。
Source
# File lib/optparse.rb, line 1675 def define_tail(*opts, &block) base.append(*(sw = make_switch(opts, block))) sw[0] end
根据给定的参数 params 创建一个选项。请参阅 新选项的参数。
如果给出了块,则该块是创建选项的处理程序。当在命令行解析过程中遇到该选项时,将使用该选项的参数(如果存在)调用该块。请参阅 选项处理程序。
Source
# File lib/optparse.rb, line 2082 def environment(env = File.basename($0, '.*'), **keywords) env = ENV[env] || ENV[env.upcase] or return require 'shellwords' parse(*Shellwords.shellwords(env), **keywords) end
解析环境变量 env 或其大写形式,并像 Shell 一样进行拆分。
env 默认为程序的基名称。
Source
# File lib/optparse.rb, line 1901 def getopts(*args, symbolize_names: false, **keywords) argv = Array === args.first ? args.shift : default_argv single_options, *long_options = *args result = {} setter = (symbolize_names ? ->(name, val) {result[name.to_sym] = val} : ->(name, val) {result[name] = val}) single_options.scan(/(.)(:)?/) do |opt, val| if val setter[opt, nil] define("-#{opt} VAL") else setter[opt, false] define("-#{opt}") end end if single_options long_options.each do |arg| arg, desc = arg.split(';', 2) opt, val = arg.split(':', 2) if val setter[opt, (val unless val.empty?)] define("--#{opt}=#{result[opt] || "VAL"}", *[desc].compact) else setter[opt, false] define("--#{opt}", *[desc].compact) end end parse_in_order(argv, setter, **keywords) result end
getopts.rb 的包装器方法。
params = ARGV.getopts("ab:", "foo", "bar:", "zot:Z;zot option") # params["a"] = true # -a # params["b"] = "1" # -b1 # params["foo"] = "1" # --foo # params["bar"] = "x" # --bar x # params["zot"] = "z" # --zot Z
选项 symbolize_names(布尔值)指定返回的 Hash 键是否应为 Symbols;默认为 false(使用 Strings)。
params = ARGV.getopts("ab:", "foo", "bar:", "zot:Z;zot option", symbolize_names: true) # params[:a] = true # -a # params[:b] = "1" # -b1 # params[:foo] = "1" # --foo # params[:bar] = "x" # --bar x # params[:zot] = "z" # --zot Z
Source
# File lib/optparse.rb, line 1419 def help; summarize("#{banner}".sub(/\n?\z/, "\n")) end
返回选项摘要字符串。
Source
# File lib/optparse.rb, line 1171 def inc(*args) self.class.inc(*args) end
请参阅 self.inc
Source
# File lib/optparse.rb, line 2042 def load(filename = nil, **keywords) unless filename basename = File.basename($0, '.*') return true if load(File.expand_path("~/.options/#{basename}"), **keywords) rescue nil basename << ".options" if !(xdg = ENV['XDG_CONFIG_HOME']) or xdg.empty? # https://specifications.freedesktop.org/basedir-spec/latest/#variables # # If $XDG_CONFIG_HOME is either not set or empty, a default # equal to $HOME/.config should be used. xdg = ['~/.config', true] end return [ xdg, *ENV['XDG_CONFIG_DIRS']&.split(File::PATH_SEPARATOR), # Haiku ['~/config/settings', true], ].any? {|dir, expand| next if !dir or dir.empty? filename = File.join(dir, basename) filename = File.expand_path(filename) if expand load(filename, **keywords) rescue nil } end begin parse(*File.readlines(filename, chomp: true), **keywords) true rescue Errno::ENOENT, Errno::ENOTDIR false end end
从文件名称(如 filename)加载选项。当文件不存在时,不执行任何操作。返回是否成功加载。
filename 默认为程序在 ~/.options 目录下的基名称(不带后缀),然后是 XDG 和 Haiku 标准位置下的基名称(带 '.options' 后缀)。
可选的 into 关键字参数的功能与方法 parse 接受的功能完全相同。
Source
# File lib/optparse.rb, line 1473 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 q, a = nil has_arg = false values = nil 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 !Completion.completable?(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, Set if Array === o o, v = o.partition {|v,| Completion.completable?(v)} values = notwice(v, values, 'values') unless v.empty? next if o.empty? end 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 Range values = notwice(o, values, 'values') when Module raise ArgumentError, "unsupported argument type: #{o}", ParseError.filter_backtrace(caller(4)) when *ArgumentStyle.keys style = notwice(ArgumentStyle[o], style, 'style') when /\A--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}" (q = q.downcase).tr!('_', '-') long << "no-#{q}" nolong << q when /\A--\[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}" (o = q.downcase).tr!('_', '-') long << o not_pattern, not_conv = search(:atype, FalseClass) unless not_style not_style = Switch::NoArgument nolong << "no-#{o}" when /\A--([^\[\]=\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}" (o = q.downcase).tr!('_', '-') long << o when /\A-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/ 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 else has_arg = true end sdesc << "-#{q}" short << Regexp.new(q) when /\A-(.)(.+)?/ 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 /\A=/ style = notwice(default_style.guess(arg = o), style, 'style') default_pattern, conv = search(:atype, Object) unless default_pattern else desc.push(o) if o && !o.empty? end end default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern if Range === values and klass unless (!values.begin or klass === values.begin) and (!values.end or klass === values.end) raise ArgumentError, "range does not match class" end end if !(short.empty? and long.empty?) if has_arg and default_style == Switch::NoArgument default_style = Switch::RequiredArgument end s = (style || default_style).new(pattern || default_pattern, conv, sdesc, ldesc, arg, desc, block, values) 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, values) end return s, short, long, (not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style), nolong end
Source
# File lib/optparse.rb, line 1384 def new @stack.push(List.new) if block_given? yield self else self end end
推送一个新的 List。
如果给出了块,则 yield self 并返回块的结果;否则返回 self。
Source
# File lib/optparse.rb, line 1641 def on(*opts, &block) define(*opts, &block) self end
Source
# File lib/optparse.rb, line 1664 def on_head(*opts, &block) define_head(*opts, &block) self end
Source
# File lib/optparse.rb, line 1688 def on_tail(*opts, &block) define_tail(*opts, &block) self end
Source
# File lib/optparse.rb, line 1717 def order(*argv, **keywords, &nonopt) argv = argv[0].dup if argv.size == 1 and Array === argv[0] order!(argv, **keywords, &nonopt) end
按顺序解析命令行参数 argv。当给出块时,每个非选项参数都将被 yield。当提供可选的 into 关键字参数时,解析后的选项值将通过 []= 方法存储在那里(因此它可以是 Hash,或 OpenStruct,或其他类似的 #-}对象)。
返回 argv 中未解析的其余部分。
Source
# File lib/optparse.rb, line 1726 def order!(argv = default_argv, into: nil, **keywords, &nonopt) setter = ->(name, val) {into[name.to_sym] = val} if into parse_in_order(argv, setter, **keywords, &nonopt) end
与 order 相同,但会破坏性地移除开关。非选项参数保留在 argv 中。
Source
# File lib/optparse.rb, line 1865 def parse(*argv, **keywords) argv = argv[0].dup if argv.size == 1 and Array === argv[0] parse!(argv, **keywords) end
当环境变量 POSIXLY_CORRECT 设置时,按顺序解析命令行参数 argv,否则以置换模式解析。当提供可选的 into 关键字参数时,解析后的选项值将通过 []= 方法存储在那里(因此它可以是 Hash,或 OpenStruct,或其他类似的 #-}对象)。
Source
# File lib/optparse.rb, line 1874 def parse!(argv = default_argv, **keywords) if ENV.include?('POSIXLY_CORRECT') order!(argv, **keywords) else permute!(argv, **keywords) end end
与 parse 相同,但会破坏性地移除开关。非选项参数保留在 argv 中。
Source
# File lib/optparse.rb, line 1842 def permute(*argv, **keywords) argv = argv[0].dup if argv.size == 1 and Array === argv[0] permute!(argv, **keywords) end
以置换模式解析命令行参数 argv 并返回非选项参数列表。当提供可选的 into 关键字参数时,解析后的选项值将通过 []= 方法存储在那里(因此它可以是 Hash,或 OpenStruct,或其他类似的 #-}对象)。
Source
# File lib/optparse.rb, line 1851 def permute!(argv = default_argv, **keywords) nonopts = [] order!(argv, **keywords) {|nonopt| nonopts << nonopt} argv[0, 0] = nonopts argv end
与 permute 相同,但会破坏性地移除开关。非选项参数保留在 argv 中。
Source
# File lib/optparse.rb, line 1294 def program_name @program_name || strip_ext(File.basename($0)) end
在错误消息和默认横幅中显示的程序名称,默认为 $0。
Source
# File lib/optparse.rb, line 1246 def reject(*args, &blk) top.reject(*args, &blk) end
指定拒绝类参数。
type-
参数类说明符,可以是任何对象,包括 Class。
reject(type)
Source
# File lib/optparse.rb, line 1327 def release (defined?(@release) && @release) || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE) end
发布代码
Source
# File lib/optparse.rb, line 1697 def separator(string) top.append(string, nil, nil) end
在摘要中添加分隔符。
Source
# File lib/optparse.rb, line 1409 def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk) nl = "\n" blk ||= proc {|l| to << (l.index(nl, -1) ? l : l + nl)} visit(:summarize, {}, {}, width, max, indent, &blk) to end
将选项摘要放入 to 并返回 to。如果给出了块,则 yield 每一行。
to-
输出目的地,必须具有方法 <<。默认为 []。
width-
左侧宽度,默认为 @summary_width。
max-
左侧允许的最大长度,默认为
width- 1。 indent-
缩进,默认为 @summary_indent。
Source
# File lib/optparse.rb, line 1206 def terminate(arg = nil) self.class.terminate(arg) end
终止选项解析。可选参数 arg 是一个字符串,将被推回以作为第一个非选项参数。
Source
# File lib/optparse.rb, line 1448 def to_a; summarize("#{banner}".split(/^/)) end
返回选项摘要列表。
Source
# File lib/optparse.rb, line 1367 def top @stack[-1] end
Source
# File lib/optparse.rb, line 1334 def ver if v = version str = +"#{program_name} #{[v].join('.')}" str << " (#{v})" if v = release str end end
从 program_name、版本和发布信息返回版本字符串。
Source
# File lib/optparse.rb, line 1320 def version (defined?(@version) && @version) || (defined?(::Version) && ::Version) end
Source
# File lib/optparse.rb, line 1349 def warn(mesg = $!) super("#{program_name}: #{mesg}") end