Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spawning a process in ruby, capturing stdout, stderr, getting exist status

Tags:

ruby

I want to run an executable from a ruby rake script, say foo.exe

I want the STDOUT and STDERR outputs from foo.exe to be written directly to the console I'm running the rake task from.

When the process completes, I want to capture the exit code into a variable. How do I achieve this?

I've been playing with backticks, process.spawn, system but I cant get all the behaviour I want, only parts

Update: I'm on Windows, in a standard command prompt, not cygwin

like image 972
Andrew Bullock Avatar asked Jun 15 '12 12:06

Andrew Bullock


2 Answers

system gets the STDOUT behaviour you want. It also returns true for a zero exit code which can be useful.

$? is populated with information about the last system call so you can check that for the exit status:

system 'foo.exe'
$?.exitstatus

I've used a combination of these things in Runner.execute_command for an example.

like image 124
Garry Shutler Avatar answered Oct 14 '22 21:10

Garry Shutler


backticks will get stdout captured into resulting string

foo.exe suggests you are running windows - do you have anything like cygwin installed? if you run your script within unixy shell you can do this:

result = `foo.exe 2>&1`
status = $?.exitstatus

quick googling says this should also work in native windows shell but i can't test this assupmtion

like image 44
keymone Avatar answered Oct 14 '22 22:10

keymone