简体   繁体   English

如何在Ruby中使用命令行选项?

[英]How do I use command-line options in Ruby?

How do I use command options in scripts? 如何在脚本中使用命令选项?

I have a script that connects to a device, runs commands and prints the output. 我有一个脚本可以连接到设备,运行命令并打印输出。 I would like to use a file for the hosts, and one for the user and passwd info. 我想为主机使用一个文件,为用户和passwd信息使用一个文件。 When I try to run the script I get these errors: 当我尝试运行脚本时,出现以下错误:

  1. ruby threat_detection.rb --host_file=hosts --config_file=config

     threat_detection.rb:61:in '<main>': needless argument: --host_file=hosts (OptionParser::NeedlessArgument) 
  2. ruby threat_detection.rb '--host_file=hosts' '--config_file=config'

     threat_detection.rb:61:in '<main>': needless argument: --host_file=hosts (OptionParser::NeedlessArgument) 
  3. ruby threat_detection.rb --host_file-hosts --config_file-config

     threat_detection.rb:61:in '<main>': invalid option: --host_file-hosts (OptionParser::InvalidOption) 

This is the code: 这是代码:

options ={}

opt_parser = OptionParser.new do |opt|
  opt.banner = 'Usage: opt_parser COMMAND [OPTIONS]'
  opt.on('--host_file', 'I need hosts, put them here') do |host_file|
    options[:host_file] == host_file
  end
  opt.on('--config_file', 'I need config info, put it here') do |config_file|
    options[:config_file] == config_file
  end
  opt.on('-h', '--help', 'What your looking at') do |help|
    options[:help] == help
    puts opt
  end
end

opt_parser.parse!

How do I make these options get read? 如何使这些选项得到阅读? This is my guess (based off python experience). 这是我的猜测(基于python经验)。 I'm just looking for it to print the lines right now: 我只是在寻找它来打印行:

if :config_file == true
  File.open(:config_file, r) do |params|
    puts params
  end
end

if :host_file == true
  File.open(:host_file, r) do |host|
    put host
  end
end

For taking arguments you need to use the following formats 要接受参数,您需要使用以下格式

"--switch=MANDATORY" or "--switch MANDATORY" # mandatory argument
"--switch[=OPTIONAL]"                        # optional argument
"--switch"                                   # no argument

You are currently using the third format, which is being interpreted as taking no argument. 您当前正在使用第三种格式,该格式被解释为不带任何参数。 You should use the first or second. 您应该使用第一个或第二个。

Also worth noting you probably want to be doing an assignment instead of a comparison when a flag is on 同样值得一提的是,当标记打开时,您可能希望执行赋值操作而不是比较操作

You want this 你要这个

options[:host_file] = host_file

not this 不是这个

options[:host_file] == host_file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM