Andrew Bullock
Andrew Bullock

Reputation: 37378

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

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

Upvotes: 5

Views: 2489

Answers (2)

Garry Shutler
Garry Shutler

Reputation: 32698

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.

Upvotes: 8

keymone
keymone

Reputation: 8094

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

Upvotes: 2

Related Questions