首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Trollop编写用于命令行解析的Ruby脚本?

如何使用Trollop编写用于命令行解析的Ruby脚本?
EN

Stack Overflow用户
提问于 2014-01-26 00:11:17
回答 1查看 1.3K关注 0票数 3

我最近开始使用手摇,这是一个干净而优雅的命令行选项解析器,适用于所有基于Ruby的小型命令行黑客。我发现它确实很容易使用,但起步却很困难:尽管有良好的在线文档,但没有任何东西显示如何将Trollop集成到完整的脚本中。

问:我如何将Trollop集成到我的Ruby命令行程序中?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-26 00:11:17

答:这是一个完整的例子.

使用if __FILE__ == $0的业务并不仅限于Trollop;这仅仅意味着“如果该文件作为脚本执行,请运行下面的代码”。此技术允许您将文件用作库模块,将业务逻辑与命令行解析分离开来。

代码语言:javascript
复制
#!/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

只要使用这段代码,您现在就可以尝试以下所有内容:

代码语言:javascript
复制
$ ./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/

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21357953

复制
相关文章

相似问题

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