1

If I am running IRB and I use the method mentioned here http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-60 to return the ruby version, it works fine.

irb(main):001:0> %x{ruby -v}
=> "ruby 1.9.2p290 (2011-07-09) [i386-mingw32]\n"

But when I try to do the same thing in IRB with Java, I can see it printing to screen but it does not return.

irb(main):002:0> %x{java -version}
java version "1.6.0_27"
Java(TM) SE Runtime Environment (build 1.6.0_27-b07)
Java HotSpot(TM) 64-Bit Server VM (build 20.2-b06, mixed mode)
=> ""

What method is Java using to output to the console, and how can I capture it for use inside of a ruby/rails program?

3
  • I noticed that this is definitely not a ruby issue (not that you said it was). Executing java -version > test.txt in bash results in the java info being printed to the screen and nothing going into test.txt. Commented Aug 24, 2012 at 20:45
  • I made the assumption that %x was capturing stdout, if that isn't the case what is it doing? It captures other commands like linux's %x{du -hs}, or more elaborately %x{bash -c "sudo vserver myserver exec ls"} It would be save to say these things do not explicitly return things in a ruby-friendly format and it simply gets caught in stdout... Commented Aug 24, 2012 at 20:49
  • %x captures STDOUT only. The problem is the stream you want to capture isn't STDOUT, it's STDERR. See my answer how to deal with it simply. And, it's not a case of being Ruby-friendly, it's a case of needing to know how to work with the command-line. Commented Aug 24, 2012 at 21:42

1 Answer 1

4

Java is using STDERR to print its version information. You can capture that easily by routing STDERR to STDOUT's stream, and capturing both.

asdf = `java -version 2>&1`
puts asdf

will output:

java version "1.6.0_33"
Java(TM) SE Runtime Environment (build 1.6.0_33-b03-424-10M3720)
Java HotSpot(TM) 64-Bit Server VM (build 20.8-b03-424, mixed mode)

This is a very common technique when working at the command-line. Do a man sh at the command-line, and search for REDIRECTION using "/REDIRECTION" and read from there.

Sign up to request clarification or add additional context in comments.

3 Comments

Great answer. Is there a way of marking a line that came from stderr instead of stdout?
Answeing my own question in comment, $?.exitstatus == 0 if success and == 1 if fail and == 127 if command not found
I don't understand what you mean by "marking a line". You want to tell if the line was received from STDERR vs. STDOUT? You have to use popen3 to differentiate between the two, because it captures both STDOUT and STDERR into different channels.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.