Ruby调用shell命令

本文介绍了五种在Ruby中执行Shell命令的方法:exec、system、反引号(`)、IO.popen及Open3#open3。每种方法都有其适用场景,如使用exec完全替换当前进程,system用于检查命令执行状态,反引号获取命令执行结果等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

原来发在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.

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值