Greg __ wrote in post #1006261:
I’m running a Perl script from within a Ruby script. If the script
throws an error the Ruby script continues. I’d like to catch the error
and do something.
You’re not going to be able to do that in the sense that you catch an
exception. Essentially, you are using your ruby program to tell your
operating system to go off and run another program for you.
What you can do is examine the exit code that the operating system got
from running your program using ruby’s system() method (0=success,
anything else = failure).
Or, you can use ruby’s backticks to run the program, which will return
any string the program writes to stdout. The error string
from your perl script, however, is being sent to stderr. You have a
couple
of options in that regard:
- You can use shell redirection commands to send the stderr string
into the nearest black hole
cmd = “perl my_prog.pl 2>/dev/null”
2 represents stderr, and ‘>’ redirects stderr’s output to ‘/dev/null’,
which is a place on your operating system where unwanted text can be
sent to never
be seen again.
- Or, you can redirect the stderr text to stdout:
cmd = “perl my_prog.pl 2>&1”
1 represents stdout. If you do that, ruby’s backticks will catch any
strings the program sends to stdout
and stderr. ruby’s backticks also set the variable $?, which is the
process exit code (0=success, anything else = failure). So you could
‘catch’ the error message text and check if the process exited
successfully like this:
cmd = “perl perl.pl 2>&1”
stdout_output = #{cmd}
puts “** #{stdout_output} **”
if $? != 0
puts “-- perl script error! —”
end
puts “Error calling gpsPhoto.pl:” + $! + " for photo:
ruby copies a lot of things from perl, and the $! in that line is the
current exception info for your ruby program–not your perl program.
Your ruby program doesn’t know anything about perl, and it has no idea
whether your perl program threw an exception or not. All your ruby
program can do is capture some text that your perl program outputs.
I’m running the script in TextMate and the errors do
show up in the TextMate “Running” window.
Don’t ever run programs that use subprocesses in an IDE–you can never
be sure whether the IDE is handling the subprocess correctly. Execute
your program from the command line.