在Ruby脚本中运行命令行命令

gee*_*fun 89 ruby terminal scripting command-line command-prompt

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

如果我可以将所有这些与Ruby(MySQL后端等)结合在一起,那将是很棒的.

Adr*_*ian 205

是.有几种方法:


一个.使用%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)
Run Code Online (Sandbox Code Playgroud)

这些方法将返回stdout,并将stderr重定向到程序.


用途system:

system 'echo hi' #=> true (prints 'hi')
system 'echo hi >&2' #=> true (prints 'hi' to stderr)
system 'exit 1' #=> nil
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

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


d.(ruby 1.9)使用spawn:

spawn 'sleep 1; echo one' #=> 430
spawn 'echo two' #=> 431
sleep 2
# This program will print "two\none".
Run Code Online (Sandbox Code Playgroud)

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


用途IO.popen:

io = IO.popen 'cat', 'r+'
$stdout = io
puts 'hi'
$stdout = IO.new 0
p io.read(1)
io.close
# prints '"h"'.
Run Code Online (Sandbox Code Playgroud)

此方法将返回一个重新显示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
Run Code Online (Sandbox Code Playgroud)

Open3有几个其他功能可以获得对两个输出流的显式访问.它类似于popen,但可以访问stderr.

  • 状态。成功吗?在ruby 2.4上不再为我工作,它更改为status.success?:) (2认同)

Mar*_*off 14

有几种方法可以在Ruby中运行系统命令.

irb(main):003:0> `date /t` # surround with backticks
=> "Thu 07/01/2010 \n"
irb(main):004:0> system("date /t") # system command (returns true/false)
Thu 07/01/2010
=> true
irb(main):005:0> %x{date /t} # %x{} wrapper
=> "Thu 07/01/2010 \n"
Run Code Online (Sandbox Code Playgroud)

但是如果您需要使用命令的stdin/stdout实际执行输入和输出,您可能希望查看IO::popen具体提供该功能的方法.


ohh*_*hho 7

 folder = "/"
 list_all_files = "ls -al #{folder}"
 output = `#{list_all_files}`
 puts output
Run Code Online (Sandbox Code Playgroud)