有没有办法通过 Ruby 运行命令行命令?我正在尝试创建一个小的 Ruby 程序,它可以通过命令行程序(如“screen”、“rcsz”等)拨出和接收/发送。
如果我能将所有这些与 Ruby(MySQL 后端等)结合起来,那就太好了
最佳答案
是的。有几种方式:
a. 使用 %x
或 '`':
%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.使用系统
:
system 'echo hi' #=> true (prints 'hi')
system 'echo hi >&2' #=> true (prints 'hi' to stderr)
system 'exit 1' #=> nil
如果命令成功,此方法返回 true
。它将所有输出重定向到程序。
c. 使用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. (ruby 1.9) 使用spawn
:
spawn 'sleep 1; echo one' #=> 430
spawn 'echo two' #=> 431
sleep 2
# This program will print "two\none".
此方法不等待进程退出并返回 PID。
e.使用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. 使用 Open3
(在 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。
关于ruby - 在 Ruby 脚本中运行命令行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3159945/