Ruby调用shell命令

 

原来发在diandian的几篇旧闻,也一并转到iteye上来吧。

 

1. exec

exec 'echo "hello $HOSTNAME"'

用echo命令来取代当前进程,无法知道命令是否成功

2. system

system('echo "hello $HOSTNAME"')

运行一个子shell来避免覆盖当前进程,运行成功返回true,运行失败返回false

3. ·· 反引号 

 

`echo $HOSTNAME`

运行一个子shell来避免覆盖当前进程,可以接受命令执行结果

4. IO.popen

def run(command, input='')

        IO.popen(command, 'r+') do |io|

                io.puts input

                io.close_write

                return io.read

        end 

end

run 'wc -w', 'How many words are in this string?'

 

IO.popenis a good way to run noninteractive commandscommands that read 

all their standard input at once and produce some output.

5. Open3#open3

require 'open3'

Open3.popen3('bc') do | stdin, stdout, stderr |

               Thread.new { loop { puts "STDOUT stream: #{stdout.gets}" } }

               Thread.new { loop { puts "STDERR stream: #{stderr.gets}" } }

               stdin.puts "3 * 4"

               stdin.puts "1 / 0"

               stdin.puts "2 ^ 5"

               sleep 0.1
end

    Runs a command in a subprocess. Data written to stdin can be read by the subprocess, anddata written to standard output and standard error in the subprocess will be available on thestdout and stderr streams.

 

 

你可能感兴趣的:(shell,Ruby)