在 Ruby 脚本中运行命令行命令 [英] Running command line commands within Ruby script

查看:43
本文介绍了在 Ruby 脚本中运行命令行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法通过 Ruby 运行命令行命令?我正在尝试创建一个小的 Ruby 程序,该程序可以通过screen"、rcsz"等命令行程序拨出和接收/发送.

Is there a way to run command line commands through Ruby? I'm trying to create a small little Ruby program that would dial out and receive/send through command line programs like 'screen', 'rcsz', etc.

如果我能将所有这些与 Ruby(MySQL 后端等)结合起来就好了

It would be great if I could tie all this in with Ruby (MySQL backend, etc.)

推荐答案

是的.有几种方式:

a. 使用 %x 或 '`':

a. Use %x or '`':

%x(echo hi) #=> "hi
"
%x(echo hi >&2) #=> "" (prints 'hi' to stderr)

`echo hi` #=> "hi
"
`echo hi >&2` #=> "" (prints 'hi' to stderr)

这些方法将返回标准输出,并将标准错误重定向到程序的.

These methods will return the stdout, and redirect stderr to the program's.

b. 使用system:

system 'echo hi' #=> true (prints 'hi')
system 'echo hi >&2' #=> true (prints 'hi' to stderr)
system 'exit 1' #=> nil

如果命令成功,此方法返回 true.它将所有输出重定向到程序的.

This method returns true if the command was successful. It redirects all output to the program's.

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.

用命令创建的进程替换当前进程.

That replaces the current process with the one created by the command.

d. (ruby 1.9) 使用 spawn:

d. (ruby 1.9) use spawn:

spawn 'sleep 1; echo one' #=> 430
spawn 'echo two' #=> 431
sleep 2
# This program will print "two
one".

该方法不等待进程退出并返回PID.

This method does not wait for the process to exit and returns the 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 对象,该对象代表新进程的输入/输出.这也是目前我所知道的给程序输入的唯一方法.

This method will return an IO object that reperesents the new processes' input/output. It is also currently the only way I know of to give the program input.

f. 使用 Open3(1.9.2 及更高版本)

f. Use Open3 (on 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 有几个其他函数可以显式访问两个输出流.它类似于 popen,但可以让您访问 stderr.

Open3 has several other functions for getting explicit access to the two output streams. It's similar to popen, but gives you access to stderr.

这篇关于在 Ruby 脚本中运行命令行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆