【问题标题】:Getting Console Input with Ruby's Docopt使用 Ruby 的 Docopt 获取控制台输入
【发布时间】:2015-03-04 14:59:47
【问题描述】:

我在 Ruby 中使用 Docopt 来解析我的命令选项,稍后在脚本中我使用 gets.chomp 获取控制台输入。问题是在Docopt使用options = Docopt::docopt(doc)解析之后,运行程序的所有参数仍然留在ARGF中,并且在尝试从STDIN获取之前执行gets命令从ARGF获取。

我试图清除 ARGF,但由于某种原因,ARGF.gets 试图将输入作为命令运行。我认为清除 ARGF 或使用其他输入法都可能是解决方案,但我还没有找到任何东西。我不得不想象我不是第一个尝试在 Ruby 中使用 Docopt 获得交互式命令行输入的人,所以我希望答案就在那里。

更多代码供喜欢的人使用:

#!/usr/bin/ruby

require 'docopt'

doc=<<eos
Usage:
account_creator.rb --noldap                           [options]

Options:
-h, --help                  Show help page
-l, --ldap
-n, --noldap
-s SERVER                 With or without http[s]://, followed by port
--ad
--od
-d NUM
-u USER
-p PASS
-o OUTPUT-FILE             Default behavior is to append output to file if it exists
eos

options = {}
begin
  options = Docopt::docopt(doc)
rescue Docopt::Exit => e
  puts e.message
  exit 1
end

if options['-u']
  username = options['-u']
else
  while username.eql? '' or username == nil
    puts "Enter Username:"
    username = Kernel.gets.chomp.strip
  end
end

【问题讨论】:

  • 请发布一些代码,以便我们更好地帮助您解决问题。

标签: ruby console interactive gets docopt


【解决方案1】:

这与 docopt 无关。自己试试吧:

$ cat test.rb
#!/usr/bin/ruby

puts "Enter Username:"
username = gets

$ ./test.rb something
Enter Username:
./test.rb:4:in `gets': No such file or directory - something (Errno::ENOENT)
        from ./test.rb:4:in `gets'
        from ./test.rb:4:in `<main>'

Kernel.gets 在 ruby​​ 中使用 ARGF.gets。使用 STDIN.gets 应该会让您得到预期的行为。见this SO question

【讨论】:

    猜你喜欢
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    相关资源
    最近更新 更多