将 shell 命令的输出逐行捕获到一个数组中

4
我希望能够记录rubocop违规总数,以确定我的代码库是变得更好还是更糟。我几乎没有编写ruby脚本的经验。
这是目前为止我写的脚本:
#!/usr/bin/env ruby
#script/code_coverage

var = `rubocop ../ -f fuubar -o ../coverage/rubocop_results.txt -f offenses`
puts var

所以我运行了./rails-app/script/code_coverage命令,我的终端显示:
...
--
6844  Total

当我使用var.inspect时,我会得到一个很长的字符串。我希望能够逐行阅读rubocop ../ -f ...的输出(首选),或者将每行输出捕获到数组中。
我想要做类似这样的事情:
var.each |line| do
  if line.contains('total')
    ...
    total = ...
end

这有可能吗?我猜这与将输出写入文件并逐行读取文件类似。

2个回答

5
如果您想保持简单,可以简单地拆分您的var字符串。
var = `rubocop ../ -f fuubar -o ../coverage/rubocop_results.txt -f offenses`.split("\n")

然后您可以像想要的那样迭代var

2
使用Ruby的Open3库。 Open3允许您访问stdin,stdout,stderr和一个线程,以在运行另一个程序时等待子进程。您可以像Process.spawn一样指定程序的各种属性,重定向,当前目录等。
参考链接:http://blog.bigbinary.com/2012/10/18/backtick-system-exec-in-ruby.html
require 'open3'


# Run lynx on this file.
cmd = "lynx -crawl -dump /data/feed/#{file_name}.html  > /data/feed/#{file_name}"
Open3.popen3(cmd) do |stdin, stdout, stderr, wait_thr|
   cmdout = stdout.read
   $logger.debug "stdout is:" + stdout.read
   $logger.debug "stderr is:" + stderr.read
end

$logger.debug 是什么? - Eric Francis
一个名为Lumberjack的Ruby Gem实例。如果你想要记录任何东西,我建议你去看一下它。https://github.com/bdurand/lumberjack - Sarvesh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接