六种用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
相关文档:
照例可以先看端程序
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 ......
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 ......
#一、这里是注释,是单行注释,类似于//
puts 3/5#这里是整数形式的结果
puts 3/5.0#这里是小数形式的结果
=begin
这是多行注释,实际上这也是Ruby内嵌文档格式,类似于Java doc
=end不但要有起止,还要缩进才有用。
=end
#二、连行
puts "Hello Ruby!"; puts "This is a "\
"String";# ......
#一、定义一个类
class Person
def initialize(name,age=18)
@name=name;
@age=age;
@motherland="china";
end
def talk
puts "my name is "+@name+" and I am "+@age.to_s
&nb ......
学了一个学期的C语言,看了一个星期的ruby,我才发现为什么老师说C是最基础的,假如没有一个学期的C基础,那ruby我也不用看了。
Ruby和C语言有许多的相同点和不同点,在学习ruby时,有时可以用C里面的思维来理解,就像ruby里面的方法其实就跟C的函数如出一 ......