361
If you need to escape the arguments, in Ruby 1.9 IO.popen also accepts an array:
p IO.popen(["echo", "it's escaped"]).read
In earlier versions you can use Open3.popen3:
require "open3"
Open3.popen3("echo", "it's escaped") { |i, o| p o.read }
If you also need to pass stdin, this should work in both 1.9 and 1.8:
out = IO.popen("xxd -p", "r+") { |io|
io.print "xyz"
io.close_write
io.read.chomp
}
p out # "78797a"
You use backticks:
`ls`
If you want the output redirected to a file using Kernel#system, you can do modify descriptors like this:
redirect stdout and stderr to a file(/tmp/log) in append mode:
system('ls -al', :out => ['/tmp/log', 'a'], :err => ['/tmp/log', 'a'])
For a long running command, this will store the output in real time. You can also, store the output using a IO.pipe and redirect it from Kernel#system.