Yes. There are several ways:
a. Use %x or ``:
%x(echo hi) #=> "hi\n" %x(echo hi >&2) #=> "" (prints 'hi' to stderr) `echo hi` #=> "hi\n" `echo hi >&2` #=> "" (prints 'hi' to stderr)
These methods return stdout and redirect stderr to the program.
b. Use system :
system 'echo hi'
This method returns true if the command was successful. It redirects all output to the program.
c. Use exec :
fork { exec 'sleep 60' }
This replaces the current process with the one created by the team.
d. (ruby 1.9) use spawn :
spawn 'sleep 1; echo one'
This method does not wait for the process to complete and returns a PID.
e. Use IO.popen :
io = IO.popen 'cat', 'r+' $stdout = io puts 'hi' $stdout = IO.new 0 p io.read(1) io.close # prints '"h"'.
This method returns an IO object that repeats the input / output of new processes. This is currently the only way I know to provide input to the program.
f. Use Open3 (in version 1.9.2 and later)
require 'open3' stdout,stderr,status = Open3.capture3(some_command) STDERR.puts stderr if status.successful? puts stdout else STDERR.puts "OH NO!" end
Open3 has several other features for explicit access to two output streams. It is similar to popen, but gives you access to stderr.
Adrian Jul 01 '10 at 17:03 2010-07-01 17:03
source share