是的。有以下几种方法:
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)
这些方法将返回标准输出,并将标准错误重定向到程序的。
b. Use system
:
system 'echo hi' #=> true (prints 'hi')
system 'echo hi >&2' #=> true (prints 'hi' to stderr)
system 'exit 1' #=> nil
该方法返回true
如果命令成功。它将所有输出重定向到程序的输出。
c. Use exec
:
fork { exec 'sleep 60' } # you see a new process in top, "sleep", but no extra ruby process.
exec 'echo hi' # prints 'hi'
# the code will never get here.
这会将当前进程替换为该命令创建的进程。
d.(红宝石1.9)使用spawn
:
spawn 'sleep 1; echo one' #=> 430
spawn 'echo two' #=> 431
sleep 2
# This program will print "two\none".
该方法不等待进程退出并返回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"'.
该方法将返回一个IO
代表新进程的输入/输出的对象。这也是目前我所知道的给程序输入的唯一方法。
f. Use Open3 http://ruby-doc.org/stdlib/libdoc/open3/rdoc/index.html(1.9.2 及更高版本)
require 'open3'
stdout,stderr,status = Open3.capture3(some_command)
STDERR.puts stderr
if status.successful?
puts stdout
else
STDERR.puts "OH NO!"
end
Open3
还有几个其他函数可以显式访问两个输出流。它与 popen 类似,但允许您访问 stderr。