您现在的位置是:网站首页> 编程资料编程资料
Ruby中调用执行shell命令的6种方法_ruby专题_
2023-05-26
363人已围观
简介 Ruby中调用执行shell命令的6种方法_ruby专题_
碰到需要调用操作系统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"
>> $?
=> #
>> $?.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')
=> [#
>> 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, #
>> $?
=> nil
>> pid
=> 26327
>> ignored, status = Process::waitpid2 pid
=> [26327, #
>> status.to_i
=> 256
相关内容
- ruby中执行周期性任务(定时任务)的3种方法_ruby专题_
- Ruby中实现把字符串转换为类的2种方法_ruby专题_
- CentOS 6.3下编译安装Ruby 2.0笔记_ruby专题_
- Ruby中使用SWIG编写ruby扩展模块实例_ruby专题_
- Ruby使用C++扩展实例(含C++扩展代码示例)_ruby专题_
- 使用ruby部署工具mina快速部署nodejs应用教程_ruby专题_
- Ruby中的迭代器详解_ruby专题_
- Ruby教程之注释、变量声明以及数组操作_ruby专题_
- Rails bundle命令安装mysql gem包出错的解决方法_ruby专题_
- Java 版的 Ruby 解释器 JRuby 1.7.14 发布_ruby专题_
