首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >修改拼音OptionParser错误消息

修改拼音OptionParser错误消息
EN

Stack Overflow用户
提问于 2014-01-31 04:12:29
回答 3查看 1.3K关注 0票数 1

我正在学习使用Ruby的OptionParser类。如何提高解析器错误消息的质量?以下是一个带有强制选项的标志示例,该选项必须是hourdayweekmonth之一。

代码语言:javascript
复制
opt_parser = OptionParser.new do |opts|
  opts.banner = "Usage: #{$0} [options] username"

  times = [:hour, :day, :week, :month]
  opts.on('-t', '--time=TIME', times,
          'Show messages from the last TIME (defaults to weeks)', "Avaliable options are (#{times.join(', ')})") do |time|
    o.time = time
  end
end

以下是一些示例输出。

代码语言:javascript
复制
$ ./script -t
./scraper.rb:195:in `main': missing argument: -t (OptionParser::MissingArgument)
from ./scraper.rb:210:in `<main>'

$ ./script -t not_a_value
./scraper.rb:195:in `main': invalid argument: -t not_a_value (OptionParser::InvalidArgument)
from ./scraper.rb:210:in `<main>'

我希望错误中提到可接受的值,比如invalid option for -t 'not_a_value', valid options are hour, day, week, month

EN

回答 3

Stack Overflow用户

发布于 2018-05-01 21:03:46

我用下面的方法来做:

代码语言:javascript
复制
begin
    parser.parse! ARGV
rescue OptionParser::InvalidArgument => e
#    puts e.instance_variables
#    puts e.args
#    puts e.reason
    if e.args.include? '-t'
        STDERR.puts "Invalid value of parameter -t. Availible options: #{t_options}"
        puts parser.help
        exit 1
    end
    STDERR.puts e
end

如果参数-t缺失,则打印输出紧随其后。否则,打印默认错误消息。留下了一些注释掉的“out”行,我可以帮助你在异常数据中找到更多有用的东西。

票数 2
EN

Stack Overflow用户

发布于 2014-08-22 23:42:58

OptionParser在这方面对你帮助不大,但你可以自己实现它,不会有太多麻烦,而且仍然是枯燥的。只需自己检查正确性,并在需要时抛出错误。

代码语言:javascript
复制
times = [:hour, :day, :week, :month]
opts.on('-t', '--time=TIME',
    'Show messages from the last TIME (defaults to weeks)',
    "Available options are <#{times.join ', '}>") do |time|
  times.include?(time.to_sym) or 
    raise OptionParser::ParseError.new("time must be one of <#{times.join ', '}>")
  o.time = time
end

让输出更干净一点也很好:

代码语言:javascript
复制
  begin
    p.parse!(ARGV)
  rescue OptionParser::ParseError => e
    puts e
    exit 1
  end
票数 1
EN

Stack Overflow用户

发布于 2014-01-31 04:21:04

当然,这就像这样简单:

代码语言:javascript
复制
opt_parser = OptionParser.new do |opts|
  opts.banner = "Usage: #{$0} [options] username"

  times = [:hour, :day, :week, :month]
  begin
    opts.on('-t', '--time=TIME', times,
      'Show messages from the last TIME (defaults to weeks)', "Avaliable options are (#    {times.join(', ')})") do |time|
    o.time = time
    rescue OptionParser::MissingArgument, OptionParser::InvalidArgument
      $stderr.print "Usage: -t <argument> where argument in [:hour, :day, :week, :month]"
    end
  end
end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21466551

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档