optionparser_使用OptionParser解析Ruby中的命令

optionparser

In the article discussing OptionParser's features we discussed some of the reasons that make using OptionParser in Ruby preferable to looking through ARGV manually to parse commands by hand. Now it's time to get down to learning how to use OptionParser and its features.

讨论OptionParser功能文章中,我们讨论了一些使在Ruby中使用OptionParser优于手动查看ARGV来手动解析命令的原因。 现在该开始学习如何使用OptionParser及其功能了。

The following boilerplate code will be used for all the examples in this tutorial. To try any of the examples, simply put the example's opts.on block next to the TODO comment. Running the program will print the state of the options has and ARGV, allowing you to examine the effects of your switches.

以下样板代码将用于本教程中的所有示例。 要尝试任何示例,只需将示例的opts.on块放在TODO注释旁边。 运行程序将打印选项has和ARGV的状态,使您可以检查开关的效果。


require 'optparse'
需要“ optparse”
require 'pp'
需要'pp'
# This hash will hold all of the options
#此哈希将包含所有选项
# parsed from the command-line by
#从命令行解析
# OptionParser.
#OptionParser。
options = {}
选项= {}
optparse = OptionParser.new do|opts|
optparse = OptionParser.new do | opts |
# TODO: Put command-line options here
#TODO:在此处放置命令行选项
# This displays the help screen, all programs are
#这会显示帮助屏幕,所有程序都是
# assumed to have this option.
#假定具有此选项。
opts.on( '-h', '--help', 'Display this screen' ) do
opts.on('-h','--help','显示此屏幕')do
puts opts
选择权
exit
出口
end
结束
end
结束
# Parse the command-line. Remember there are two forms
#解析命令行。 记住有两种形式
# of the parse method. The 'parse' method simply parses
解析方法的数量。 “解析”方法只是解析
# ARGV, while the 'parse!' method parses ARGV and removes
#ARGV,同时“解析!” 方法解析ARGV并删除
# any options found there, as well as any parameters for
#在那里找到的所有选项,以及
# the options. What's left is the list of files to resize.
#选项。 剩下的就是要调整大小的文件列表。
optparse.parse!
optparse.parse!
pp "Options:", options
pp“选项:”,选项
pp "ARGV:", ARGV
pp“ ARGV:”,ARGV

简单开关 ( Simple Switch )

A simple switch is an argument with no optional forms or no parameters. The effect will be to simply set a flag in the options hash. No other parameters will be passed to the on method.

一个简单的开关是没有可选形式或没有参数的参数。 结果将是在options 哈希中简单地设置一个标志。 没有其他参数将传递给on方法。


opts.on( '-s', '--simple', "Simple argument" ) do
opts.on('-s','--simple',“ Simple arguments”)做
options[:simple] = true
选项[:简单] = true
end
结束

带强制参数的开关 ( Switch with Mandatory Parameter )

Switches that take a parameter only need to state the parameter name in the long form of the switch. For example, "-f", "--file FILE" means the -f or --file switch takes a single parameter called FILE, and this parameter is mandatory. You cannot use either -f or --file without also passing it a parameter.

带有参数的交换机只需要以交换机的长格式声明参数名称。 例如, “-f”,“-file FILE”表示-f或--file开关采用单个称为FILE的参数,并且此参数是必需的。 如果不同时向其传递参数,则不能使用-f或--file。


opts.on( '-m', '--mandatory FILE', "Mandatory argument" ) do|f|
opts.on('-m','-强制性文件',“强制性参数”)do | f |
options[:mand] = f
选项[:mand] = f
end
结束

用可选参数切换 ( Switch with Optional Parameter )

Switch parameters don't have to be mandatory, they can be optional. To declare a switch parameter optional, place its name in brackets in the switch description. For example, "--logfile [FILE]" means the FILE parameter is optional. If not supplied, the program will assume a sane default, such as a file called log.txt.

开关参数不是必需的,它们可以是可选的。 要声明开关参数为可选,请将其名称放在开关说明中的括号中。 例如, “-logfile [FILE]”表示FILE参数是可选的。 如果未提供,则该程序将采用默认设置,例如名为log.txt的文件。

In the example, the idiom a = b || c is used. This is just shorthand for "a = b, but if b is false or nil, a = c".

在此示例中,习语a = b || 使用c 。 这只是“ a = b,但如果b为false或nil,则a = c”的简写。


opts.on( '-o', '--optional [OPT]', "Optional argument" ) do|f|
opts.on('-o','--optional [OPT]',“ Optional arguments”)do | f |
options[:opt] = f || "nothing"
选项[:opt] = f || “没有”
end
结束

自动转换为浮动 ( Automatically Convert to Float )

OptionParser can automatically convert argument to some types. One of these types is Float. To automatically convert your arguments to a switch to Float, pass Float to the on method after your switch description strings.

OptionParser可以自动将参数转换为某些类型。 这些类型之一是Float。 要将参数自动转换为Float的开关,请在开关描述字符串之后将Float传递给on方法。

Automatic conversions are handy. Not only do they save you the step of converting the string to the desired type, but also check the format for you and will throw an exception if it is formatted incorrectly.

自动转换很方便。 它们不仅为您节省了将字符串转换为所需类型的步骤,而且还为您检查了格式,如果格式错误,则会引发异常。


opts.on( '-f', '--float NUM', Float, "Convert to float" ) do|f|
opts.on('-f','--float NUM',Float,“转换为浮点数”)do | f |
options[:float] = f
选项[:float] = f
end
结束

Some other types that OptionParser can convert to automatically include Time and Integer.

OptionParser可以转换为自动转换的其他一些类型包括“时间”和“整数”。

参数列表 ( Lists of Arguments )

Arguments can be interpreted as lists. This can be seen as converting to an array, as you converted to Float. While your option string can define the parameter to be called "a,b,c", OptionParser will blindly allow any number of elements in the list. So, if you need a specific number of elements, be sure to check the array length yourself.

参数可以解释为列表。 可以将其视为转换为数组,就像转换为Float一样。 虽然您的选项字符串可以将参数定义为“ a,b,c”,但OptionParser会盲目地允许列表中包含任意数量的元素。 因此,如果需要特定数量的元素,请确保自己检查数组长度。


opts.on( '-l', '--list a,b,c', Array, "List of parameters" ) do|l|
opts.on('-l','--list a,b,c',Array,“参数列表”)do | l |
options[:list] = l
选项[:列表] = l
end
结束

一组参数 ( Set of Arguments )

Sometimes it makes sense to restrict arguments to a switch to a few choices. For example, the following switch will only take a single mandatory parameter, and the parameter must be one of yes, no or maybe. If the parameter is anything else at all, an exception will be thrown.

有时,将参数限制为只能选择几个选项是有意义的。 例如,以下开关将仅采用单个强制性参数,并且该参数必须是yesnomay中的一个 。 如果该参数是其他任何参数,则将引发异常。

To do this, pass a list of acceptable parameters as symbols after the switch description strings.

为此,请在开关描述字符串之后将可接受参数的列表作为符号传递。


opts.on( '-s', '--set OPT', [:yes, :no, :maybe], "Parameters from a set" ) do|s|
opts.on('-s','--set OPT',[:yes,:no,:maybe],“来自集合的参数”)do | s |
options[:set] = s
选项[:set] = s
end
结束

否定形式 ( Negated Forms )

Switches can have a negated form. The switch --negated can have one that does the opposite effect, called --no-negated. To describe this in the switch description string, place the alternative portion in brackets: --[no-]negated. If the first form is encountered, true will be passed to the block, and false will be blocked if the second form is encountered.

开关可以取反形式。 --negated可以具有一个没有相反的作用的开关,叫做--no-否定 。 要在开关描述字符串中对此进行描述,请将替代部分放在方括号中: -[no-] negated 。 如果遇到第一种形式,则将true传递给该块,如果遇到第二种形式,则false将被阻止。


opts.on( '-n', '--[no-]negated', "Negated forms" ) do|n|
opts.on('-n','-[no-] negated',“ Negated form”)do | n |
options[:neg] = n
选项[:neg] = n
end
结束

翻译自: https://www.thoughtco.com/using-optionparser-2907754

optionparser

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值