Ruby中调用执行shell命令的6种方法

编程入门 行业动态 更新时间:2024-10-10 04:22:10

碰到需要调用操作系统shell命令的时候,ruby为我们提供了六种完成任务的方法:

1.exec方法:

kernel#exec方法通过调用指定的命令取代当前进程例子:

复制代码 代码如下: $ irb >> exec 'echo "hello $hostname"' hello nate.local $

值得注意的是,exec方法用echo命令来取代了irb进程从而退出了irb。主要的缺点是,你无法从你的ruby脚本里知道这个命令是成功还是失败。

2.system方法

kernel#system方法操作命令同上, 但是它是运行一个子shell来避免覆盖当前进程。如果命令执行成功则返回true,否则返回false。复制代码 代码如下:$ irb >> system 'echo "hello $hostname"' hello nate.local => true >> system 'false' => false >> puts $? 256 => nil >>

3.反引号(backticks,esc键下面那个键)

复制代码 代码如下:$ irb >> today = `date` => "mon mar 12 18:15:35 pdt 2007n" >> $? => #<process::status: pid=25827,exited(0)> >> $?.to_i => 0这种方法是最普遍的用法了。它也是运行在一个子shell中。

4.io#popen

复制代码 代码如下: $ irb >> io.popen("date") { |f| puts f.gets } mon mar 12 18:58:56 pdt 2007 => nil

5.open3#popen3

复制代码 代码如下:$ irb >> stdin, stdout, stderr = open3.popen3('dc') => [#<io:0x6e5474>, #<io:0x6e5438>, #<io:0x6e53d4>] >> stdin.puts(5) => nil >> stdin.puts(10) => nil >> stdin.puts("+") => nil >> stdin.puts("p") => nil >> stdout.gets => "15n"

6.open4#popen4

复制代码 代码如下:$ irb >> require "open4" => true >> pid, stdin, stdout, stderr = open4::popen4 "false" => [26327, #<io:0x6dff24>, #<io:0x6dfee8>, #<io:0x6dfe84>] >> $? => nil >> pid => 26327 >> ignored, status = process::waitpid2 pid => [26327, #<process::status: pid=26327,exited(1)>] >> status.to_i => 256

  • 0
  • 0
  • 0
  • 0
  • 0

更多推荐

Ruby中调用执行shell命令的6种方法

本文发布于:2023-06-10 18:42:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/616565.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:种方法   命令   Ruby   shell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!