optionparser_用Ruby方式解析命令行选项(OptionParser)

optionparser

Ruby comes equipped with a powerful and flexible tool to parse command-line options, OptionParser. Once you learn how to use this, you'll never go back to looking through ARGV manually. OptionParser has a number of features that make it quite appealing to Ruby programmers. If you've ever parsed options by hand in Ruby or C, or with the getoptlong C function, you'll see how welcome some of these changes are.

Ruby配备了强大而灵活的工具来解析命令行选项OptionParser。 一旦学习了如何使用它,您将永远不会回到手动浏览ARGV的方式。 OptionParser具有许多功能,使其对Ruby程序员非常有吸引力。 如果您曾经使用Ruby或C手动解析过选项,或者使用getoptlong C函数来解析了这些选项,您将看到其中一些更改的受欢迎程度。

  • OptionParser is DRY. You only have to write the command-line switch, its arguments, the code to run when it's encountered, and the command-line switch description once in your script. OptionParser will automatically generate help screens for you from this description, as well as infer everything about the argument from its description. For example, it will know the --file [FILE] option is optional and takes a single argument. Also, it will know that --[-no]-verbose is really two options and will accept both forms.

    OptionParser是DRY 您只需在脚本中编写一次命令行开关,其参数,遇到该命令时要运行的代码以及命令行开关说明。 OptionParser将根据此描述自动为您生成帮助屏幕,并根据其描述推断有关参数的所有内容。 例如,它将知道--file [FILE]选项是可选的,并且带有单个参数。 同样,它将知道-[-no--verbose]实际上是两个选项,并且将接受两种形式。

  • OptionParser will automatically convert options to a specific class. If the option takes an integer, it can convert any string passed on the command-line to an integer. This cuts down on some of the tedium involved in parsing command-line options.

    OptionParser将自动将选项转换为特定的类。 如果该选项采用整数,则可以将在命令行上传递的任何字符串转换为整数。 这减少了解析命令行选项所涉及的一些乏味工作。

  • Everything is very contained. All of the options are in the same place, and the effect of the option is right along-side the definition for the option. If options have to be added, changed or someone simply wants to see what they do, there is only one place to look. Once the command-line is parsed, a single Hash or OpenStruct will hold the results.

    一切都包含在内。 所有选项都在同一位置,并且选项的作用就在选项定义的旁边。 如果必须添加,更改选项,或者某人仅想查看其功能,则只能查看一个地方。 命令行解析后,将由单个Hash或OpenStruct保存结果。

已经足够了,给我看一些代码 ( Enough Already, Show Me Some Code )

So here's a simple example of how to use OptionParser. It doesn't use any of the advanced features, just the basics. There are three options, and one of them takes a parameter. All of the options are mandatory. There are the -v/--verbose and -q/--quick options, as well as the -l/--logfile FILE option. Additionally, the script takes a list of files independent of the options.

因此,这是有关如何使用OptionParser的简单示例。 它不使用任何高级功能,仅使用基本功能。 有三个选项,其中一个带有参数。 所有选项都是强制性的。 有-v /-verbose-q /-quick选项,以及-l /-logfile FILE选项。 此外,该脚本采用与选项无关的文件列表。

 #!/usr/bin/env ruby
 # A script that will pretend to resize a number of images
 require 'optparse'
 # This hash will hold all of the options
 # parsed from the command-line by
 # OptionParser.
 options = {}
 optparse = OptionParser.new do|opts|
   # Set a banner, displayed at the top
   # of the help screen.
   opts.banner = "Usage: optparse1.rb [options] file1 file2 ..."
   # Define the options, and what they do
   options[:verbose] = false
   opts.on( '-v', '--verbose', 'Output more information' ) do
     options[:verbose] = true
   end
   options[:quick] = false
   opts.on( '-q', '--quick', 'Perform the task quickly' ) do
     options[:quick] = true
   end
   options[:logfile] = nil
   opts.on( '-l', '--logfile FILE', 'Write log to FILE' ) do|file|
     options[:logfile] = file
   end
   # This displays the help screen, all programs are
   # assumed to have this option.
   opts.on( '-h', '--help', 'Display this screen' ) 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
 # any options found there, as well as any parameters for
 # the options. What's left is the list of files to resize.
 optparse.parse!
 puts "Being verbose" if options[:verbose]
 puts "Being quick" if options[:quick]
 puts "Logging to file #{options[:logfile]}" if options[:logfile]
 ARGV.each do|f|
   puts "Resizing image #{f}..."
   sleep 0.5
 end

检查代码 ( Examining the Code )

To start off with, the optparse library is required. Remember, this isn't a gem. It comes with Ruby, so there's no need to install a gem or require rubygems before optparse.

首先,需要optparse库。 记住,这不是宝石 。 它是Ruby附带的,因此在optparse之前无需安装gem或rubygems

There are two interesting objects in this script. The first is options, declared at the top-most scope. It's a simple empty hash. When options are defined, they write their default values to this hash. For example, the default behavior is for this script to not be verbose, so options[:verbose] is set to false. When options are encountered on the command-line, they'll change the values in options to reflect their effect. For example, when -v/--verbose is encountered, it will assign true to options[:verbose].

该脚本中有两个有趣的对象。 第一个是options ,在最高作用域中声明。 这是一个简单的空哈希 。 定义选项后,它们会将其默认值写入此哈希。 例如,此脚本的默认行为是冗长,因此options [:verbose]设置为false。 在命令行上遇到选项时,它们将更改选项中的值以反映其效果。 例如,当遇到-v /-verbose时,它将为true分配给options [:verbose]

The second interesting object is optparse. This is the OptionParser object itself. When you construct this object, you pass it a block. This block is run during construction and will build a list of options in internal data structures, and get ready to parse everything. It's in this block that all the magic happens. You define all the options here.

第二个有趣的对象是optparse 。 这是OptionParser对象本身。 构造此对象时,将其传递给一个块。 此块在构建期间运行,将在内部数据结构中构建选项列表,并准备分析所有内容。 正是在这个区块中,所有的魔力发生了。 您在此处定义所有选项。

定义选项 ( Defining Options )

Each option follows the same pattern. You first write the default value into the hash. This will happen as soon as the OptionParser is constructed. Next, you call the on method, which defines the option itself. There are several forms of this method, but only one is used here. The other forms allow you to define automatic type conversions and sets of values an option is restricted to. The three arguments used here are the short form, long form, and description of the option.

每个选项都遵循相同的模式。 您首先将默认值写入哈希。 一旦构造OptionParser,就会发生这种情况。 接下来,调用on 方法 ,该方法定义了选项本身。 此方法有多种形式,但此处仅使用一种形式。 其他形式允许您定义选项限制的自动类型转换和值集。 此处使用的三个参数是短格式,长格式和选项说明。

The on method will infer a number of things from the long form. One thing is will infer is the presence of any parameters. If there are any parameters present on the option, it will pass them as parameters to the block.

on方法将从长格式中推断出许多东西。 可以推断的一件事是任何参数的存在。 如果选项上存在任何参数,它将作为参数传递给块。

If the option is encountered on the command-line, the block passed to the on method is run. Here, the blocks don't do much, they just set values in the options hash. More could be done, such as checking that a file referred to exists, etc. If there are any errors, exceptions can be thrown from these blocks.

如果在命令行上遇到该选项,则运行传递给on方法的块。 在这里,这些块的作用不大,它们只是在选项哈希中设置值。 可以做更多的事情,例如检查所引用的文件是否存在等。如果有任何错误,则可以从这些块中引发异常。

Finally, the command-line is parsed. This happens by calling the parse! method on an OptionParser object. There are actually two forms of this method, parse and parse!. As the version with the exclamation point implies, it is destructive. Not only does it parse the command-line, but it will remove any options found from ARGV. This is an important thing, it will leave only the list of files supplied after the options in ARGV.

最后,命令行被解析。 这是通过调用解析发生的 OptionParser对象上的方法。 此方法实际上有两种形式,即parseparse! 。 正如带有感叹号的版本所暗示的那样,它具有破坏性。 它不仅解析命令行,还将删除从ARGV找到的所有选项。 这很重要,它将仅保留ARGV中选项之后提供的文件列表。

翻译自: https://www.thoughtco.com/optionparser-parsing-command-line-options-2907753

optionparser

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值