易截截图软件、单文件、免安装、纯绿色、仅160KB

六种用ruby调用执行shell命令的方法

六种用ruby调用执行shell命令的方法
碰到需要调用操作系统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"
&n


相关文档:

自动化测试之路(三) ruby里的get与set方法

照例可以先看端程序
class Person
 
  def initialize( name,age=18 )
    @name = name
    @age = age
    @motherland = "China"
  end
 
  def talk
    puts "my name is "+@name+", age is "+@age.to_s
 &n ......

升级到snow leopard后ruby的问题

1. ruby已成为1.87 2. 必须先安装安装光盘里的新的xcode,在"optional"目录里 3. 可能需要重新安装macport http://trac.macports.org/wiki/Migration 4. 或者升级macport http://weblog.rubyonrails.org/2009/8/30/upgrading-to-snow-leopard $ sudo port selfupdate
$ sudo port sync
$ sudo port upgrade --force insta ......

交互式 Ruby Shell irb

irb 是从命令行运行的
irb 的命令行选项(摘自 Porgramming Ruby 第二版)
-f
禁止读取~/.irbrc Suppress reading ~/.irbrc.
-m
数学模式(支持分数和矩阵) Math mode (fraction and matrix support is available).
-d
设置#DEBUG为true(同ruby -d一样)  Set $DEBUG to true (same as ``ruby -d'').
-r lo ......

菜鸟和RMXP和Ruby语言

      喜欢玩阿月系列RPG游戏的我,跟不少童鞋一样下了RPGMakerXP来瞻仰一下。当时觉得这个软件太方便了,用鼠标随便点点就能弄出来个有趣的小游戏。因为里面不仅自带不少地图和人物行走图等素材,容易上手的操作方式也让自己大有成就感……可是游戏毕竟是离不开编程,解开游戏包,看 ......

Fix Thrift 0.2.0 Installation with Ruby 1.9.1

When I try the command "gem install thrift" with Ruby 1.9.1, I got a compilation error with something related to a C function "strlcpy()".
Then I searched the web. It seems I am not alone and the community know it.
However I do not want to wait for official update, I want to ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号