Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | CLI | Play Well with Others | Use STDOUT and STDERR to Send Output to the Correct Stream

概要

書籍 Build Awesome Command-Line Applications in Ruby2

Play Well with Others

詳細

標準出力はSTDOUTに、標準エラーはSTDERRに出力します。
標準エラーの出力には

STDERR.puts "エラーメッセージ"
warn "エラーメッセージ"

の両方が利用できます。

サンプルコード

require 'open3'

command = ARGV.first
stdout_str, stderr_str, exit_status = Open3.capture3(command)

if exit_status == 0
  puts "stdout_str=#{stdout_str}"
else
  STDERR.puts "stderr_str=#{stderr_str}"
  warn "stderr_str=#{stderr_str}"
  exit false
end

出力

$ ruby 1.rb 'rspec -v'
stdout_str=2.14.8

$ ruby 1.rb 'which hoge'
stderr_str=which: no hoge in (・・・some path・・・)
stderr_str=which: no hoge in (・・・some path・・・)