如何使用Trollop进行命令行解析来制作Ruby脚本? [英] How do I make a Ruby script using Trollop for command line parsing?

查看:86
本文介绍了如何使用Trollop进行命令行解析来制作Ruby脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用 Trollop ,这是我所有小型Ruby的简洁,优雅的命令行选项解析器基于命令行的黑客。我发现它确实很容易使用,但是上手却很困难:尽管有很好的在线文档,但是没有任何东西可以说明如何将Trollop整合到一个完整的脚本中。

I've recently started using Trollop, a clean and elegant command line option parser for all my small Ruby-based command line hacks. I found it was really easy to use, but getting started was difficult: despite good online documentation, there wasn't anything that showed how to incorporate Trollop into a complete script.

Q:如何将Trollop纳入我的Ruby命令行程序?

Q: How can I incorporate Trollop into my Ruby command-line program?

推荐答案

A:这是一个独立的示例。

A: Here is a self-contained example.

具有 if __FILE__ == $ 0 的业务并非特定于Trollop;这仅表示如果此文件作为脚本执行,请运行以下代码。这种技术允许您将文件用作库模块,从而将业务逻辑与命令行解析分开。

The business with if __FILE__ == $0 isn't specific to Trollop; that just means "run the following code if this file is executed as a script". This technique allows you use the file as a library module, separating the business logic from the command line parsing.

#!/usr/bin/env ruby
# 
# This is a near-minimal ruby script to demonstrate trollop, a simple
# and elegant command-line parsing package.  To run, copy this file to
# 'trollop_demo.rb' and make it executable by
#   $ chmod +x trollop_demo.rb
# Then run it via:
#   $ ./trollop_demo.rb <your args here>
# For more info on Trollop, see http://trollop.rubyforge.org/
require 'trollop'

# A trivial program...
def main_method(filename, options)
  puts("filename = #{filename}, options = #{options}")
end

# Execute this part when the file is run as a script
if __FILE__ == $0
  opts = Trollop::options do
    version "#{$0} Version 3.14159 (C) 2041 Spacely Sprockets, Inc."
    banner <<-EOS
#{$0} is a command-line program to demonstrate trollop
Usage:
        #{$0} [options] <filename>
where [options] are zero or more of:
EOS
    opt :verbose, "Print extra information."
    opt :dry_run, "Don't actually do anything.", :short => "-n"
  end
  filename = ARGV.shift
  if (filename.nil?) || (!File.exist?(filename))
    Trollop::die "filename must be given and name an existing file"
  else
    main_method(filename, opts)
  end
end

仅需这段代码,您现在就可以尝试所有这些操作:

With just that bit of code, you can now try all these things:

$ ./trollop_demo.rb 
$ ./trollop_demo.rb a_file_that_doesn't_exist
$ ./trollop_demo.rb --version
$ ./trollop_demo.rb --help
$ ./trollop_demo.rb trollop_demo.rb
$ ./trollop_demo.rb --dry-run trollop_demo.rb
$ ./trollop_demo.rb --no-dry-run trollop_demo.rb
$ ./trollop_demo.rb --verbose trollop_demo.rb
$ ./trollop_demo.rb -v trollop_demo.rb

有关更多信息,请参见 http://trollop.rubyforge.org/

For more information, see http://trollop.rubyforge.org/

这篇关于如何使用Trollop进行命令行解析来制作Ruby脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆