ruby-从入门到放弃-调用外部命令的实现方式-Open3

open3的使用说明

我在这里就不重复造轮子了,直接使用腾讯云的open3的文档来讲解open3里面的方法以及使用说明:文档地址

着重讲解一下open3.popen3的使用

popen3(*cmd, **opts, &block) Show source 

打开stdin,stdout和stderr流并启动外部可执行文件。另外,创建一个等待启动的进程的线程。线程有一个pid方法和一个线程变量:pid,它是启动进程的pid。

块形式:

Open3.popen3([env,] cmd... [, opts]) {|stdin, stdout, stderr, wait_thr|
  pid = wait_thr.pid # pid of the started process.
  ...
  exit_status = wait_thr.value # Process::Status object returned.
}

非块形式:

stdin, stdout, stderr, wait_thr = Open3.popen3([env,] cmd... [, opts])
pid = wait_thr[:pid]  # pid of the started process
...
stdin.close  # stdin, stdout and stderr should be closed explicitly in this form.
stdout.close
stderr.close
exit_status = wait_thr.value  # Process::Status object returned.

open3.popen3的例子

def executeCommand(command)
    Open3.popen3(command) do |stdin, stdout, stderr, status|
      stdin.write command
      stdin.close
      stdout.each_line {
        |line| puts line
      }
      stdout.close
      if !status.value.success?
        return stderr.read()
      end
    end
    return "success"
  end

stdin: 方法的入参
stdout:命令的输出,可以打印外部命令执行的日志
stderr:错误的输出
status:执行状态

使用open3.popen3怎么将错误作为返回值

 if !status.value.success?
      return stderr.read()
 end
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

特特专属

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值