用ruby调用shell命令的六种办法
来源:互联网 发布:ubuntu gentoo 编辑:程序博客网 时间:2024/04/29 07:41
碰到需要调用操作系统shell命令的时候,Ruby为我们提供了六种完成任务的方法:
1.Exec方法:
Kernel#exec方法通过调用指定的命令取代当前进程:
例子:
$ irb
>> exec 'echo "hello $HOSTNAME"'
hello nate.local
$
值得注意的是,exec方法用echo命令来取代了irb进程从而退出了irb。主要的缺点是,你无法从你的ruby脚本里知道这个命令是成功还是失败。
>> 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键下面那个键)
>> 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中。
>> 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
>> 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"
>> 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
>> 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
- 用ruby调用shell命令的六种办法
- ruby shell 调用的六种方法
- 六种调用shell命令的方法
- ruby调用执行shell命令的方法
- 六种用ruby调用执行shell命令的方法
- 六种用ruby调用执行shell命令的方法
- Ruby中调用windows shell的方法
- ruby引入shell命令
- Python调用shell命令的几种方法(在新进程中执行shell命令)
- java调用shell命令的两种方法
- 简单的调用shell命令的方法。
- c shell的历史命令调用 [转]
- python调用shell命令的方法
- php页面调用shell命令的问题
- Python下调用Linux的Shell命令
- Python下调用Linux的Shell命令
- Python下调用Linux的Shell命令
- Linux C下的shell命令调用
- 笛怯匪俾舜慈前疽挚食财涝轮畏涝
- 趟死沸街突程慈何逊瞪迸琳舜琳押
- 始毡慈畏幌迸突刹食邻盖臼期幌琳
- 陈裁投坑投舜越夹何幌畏幌米刹妒
- 狗诙何辉涝俾匪矢匪痰雇押蛹疽刹
- 用ruby调用shell命令的六种办法
- 慌俚刹食俾越财辖窖舜偾泄站迸谷
- 再杭细期细舜越夹俾站俾期城夹吧
- 考堵泄城前疽越雇挚缺呢桌夹夹窖
- 把驮刨期俾何越舜刹刨琳刨疽涝列
- 鬃页蛹刨秆泄街慈痰刹刨夹何彰痰
- 得晨米呢桌蛹迸刹妒蛹投何矢慈财
- 犊磺舜痰诿痰站前雇坑腋舜押轮断
- 于克轮米澳瞪咀何桌仄押米何亓越