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

有没有办法通过Ruby运行命令行命令? 我正在尝试创build一个小的Ruby程序,通过命令行程序(如“screen”,“rcsz”等)拨出和接收/发送。

如果我可以将所有这些与Ruby(MySQL后端等)绑定在一起,

是。 有几种方法:


一个。 使用%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) 

这些方法将返回stdout,并将stderrredirect到程序的。


使用system

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

如果命令成功,则此方法返回true 。 它将所有输出redirect到程序。


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. 

用当前命令创build的进程replace当前进程。


d。 (ruby1.9)使用spawn

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

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


使用IO.popen

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

此方法将返回一个表示新进程input/输出的IO对象。 这也是目前我知道给程序input的唯一方法。


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还有其他一些function可以显式访问两个输出stream。 它与popen类似,但是可以访问stderr。

有几种方法可以在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" 

但是,如果你需要用命令的stdin / stdout实际执行input和输出,你可能会想看看IO::popen方法,它专门提供这个工具。

  folder = "/" list_all_files = "ls -al #{folder}" output = `#{list_all_files}` puts output 

是的,这当然是可行的,但是实现的方法依赖于所述的“命令行”程序是以“全屏”还是命令行模式运行。 为命令行编写的程序倾向于读取STDIN并写入STDOUT。 这些可以在Ruby中使用标准的反引号方法和/或system / exec调用直接调用。

如果程序以“全屏”模式如屏幕或vi操作,则方法必须不同。 对于这样的程序,您应该查找“expect”库的Ruby实现。 这将允许您编写您希望在屏幕上看到的内容以及在屏幕上显示特定字符​​串时要发送的内容。

这不太可能是最好的方法,你应该看看你想要实现的目标,并find相关的库/创业板,而不是试图自动化现有的全屏应用程序。 作为一个例子,“ 在Ruby中需要串口通信的帮助 ”来处理串口通信,如果你想用你提到的特定程序来实现这个function,就可以使用前缀来拨号。