【问题标题】:Capture output of shell command, line by line, into an array将 shell 命令的输出逐行捕获到数组中
【发布时间】:2014-05-02 23:20:08
【问题描述】:

我想捕获 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

这可能吗?我想这类似于将输出写入文件然后逐行读取文件。

【问题讨论】:

    标签: ruby-on-rails ruby shell stdout rubocop


    【解决方案1】:

    如果您想保持简单,您可以简单地拆分您的 var 字符串。

    var = `rubocop ../ -f fuubar -o ../coverage/rubocop_results.txt -f offenses`.split("\n")
    

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

    【讨论】:

      【解决方案2】:

      使用 ruby​​ 的 open3 库。 Open3 允许您访问标准输入、标准输出、标准错误和一个线程以在运行另一个程序时等待子进程。您可以将程序的各种属性、重定向、当前目录等指定为 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
      • 名为伐木工人的红宝石实例。如果您尝试记录任何内容,我建议您检查一下。 github.com/bdurand/lumberjack
      猜你喜欢
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多