一起学习网 一起学习网


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

网络编程 Ruby中调用执行shell命令的6种方法 06-22

碰到需要调用操作系统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

Ruby使用C++扩展实例(含C++扩展代码示例)
早年写过用C+++SWIG写Ruby插件的文,但实际中还是以原生C++写Ruby扩展,因为也相当简单。但长久没用还是会忘记,不得不翻以前的老代码回忆,写下这篇

Ruby中使用SWIG编写ruby扩展模块实例
在使用ruby/rails的过程中,确实发现有时性能不尽人意,如生成一个拥有600项的item的3层树形结构目录要花去20ms,为提高性能在学习用c/c++写ruby模块的过

CentOS 6.3下编译安装Ruby 2.0笔记
LINUX操作系统:CentOS6.364bitRuby:ruby-2.0.0-p247一.安装开发包(使用默认CENTOS更新源)#yuminstallopenssl*openssl-develzlib-develgccgcc-c++makeautoconfreadline-develcurl-develexpat-develg


编辑:一起学习网

标签:命令,方法,进程,新源,的是