From: "Ara.T.Howard" Date: 2004-07-23T05:02:01+09:00 Subject: Re: [NUBY] Reading stderr, stdout and the exit status of a process On Fri, 23 Jul 2004, Alexey Verkhovsky wrote: > Problem: call an external process, wait till it finishes, get its stdout > and stderr as Strings, as well as the exit status. > > My current approximation of the solution: > > stdout = IO.popen("myprocess.sh").readlines > exitStatus = $? > > It doesn't work. exitStatus comes out as nil. I probably understand why. > > Naturally, one can always bite the bullet and write the whole story > (open a Process, attach two reader threads, direct all output streams > into Ruby strings, wait till the Process quits, etc). This would be a > lot of code for a common scripting task, and from past experiences doing > same thing with C and Java, there are a few interesting surprises. > > Can some enlightened soul please show me The Ruby Way to do it all in > one line? Reference to an appropriate page in the Pickaxe that I should > have RTFM'd not to ask this silly question would be even better :) > > Domo arigato in advance. > > Best regards, > Alexey Verkhovsky see http://raa.ruby-lang.org/project/session/ example: jib:~ > cat a.rb require 'session' sh = Session.new # # example 0 # puts '---' stdout, stderr = sh.execute 'ls no-exist' puts "stdout : #{ stdout }" puts "stderr : #{ stderr }" puts "exitstatus : #{ sh.exitstatus }" # # example 1 # puts '---' sh.execute("ls #{ __FILE__ }") do |stdout,stderr| puts "stdout : #{ stdout }" if stdout puts "stderr : #{ stderr }" if stderr end puts "exitstatus : #{ sh.exitstatus }" # # example 2 # puts '---' sh.outproc = proc{|stdout| puts "stdout : #{ stdout }"} sh.errproc = proc{|stderr| puts "stderr : #{ stderr }"} sh.execute 'echo $$' puts "exitstatus : #{ sh.exitstatus }" jib:~ > ruby a.rb --- stdout : stderr : ls: no-exist: No such file or directory exitstatus : 1 --- stdout : a.rb exitstatus : 0 --- stdout : 16452 exitstatus : 0 you can do almost all of this using open3, but not exitstatus. it also requires you to spawn a new process for every command if you want to distinguish output. regards. -a -- =============================================================================== | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | A flower falls, even though we love it; | and a weed grows, even though we do not love it. | --Dogen ===============================================================================