通过Scala Process执行Shell脚本且收集返回的结果

需求:通过Scala Process执行Shell脚本且收集返回的结果

package tools

import java.util.concurrent.LinkedBlockingQueue

import scala.sys.process.{Process, ProcessBuilder, ProcessLogger}

/** *
  * 收集Linux脚本命令返回的结果
  */
object StreamProcessLogger {
  private val nonzeroException = true

  def run(processBuilder: ProcessBuilder): (Process, Stream[String]) = {
    val logger = new StreamProcessLogger
    val process = processBuilder.run(logger)
    waitForExitInAnotherThread(process, logger)
    (process, logger.stream)
  }

  private def waitForExitInAnotherThread(process: Process, logger: StreamProcessLogger) = {
    val thread = new Thread() {
      override def run() = {
        logger.setExitCode(process.exitValue())
      }
    }
    thread.start()
  }
}

private class StreamProcessLogger extends ProcessLogger {
  val queue = new LinkedBlockingQueue[Either[Int, String]]

  override def buffer[T](f: => T): T = f

  override def out(s: => String): Unit = queue.put(Right(s))

  override def err(s: => String): Unit = queue.put(Right(s))

  def stream = next()

  def setExitCode(exitCode: Int) = queue.put(Left(exitCode))

  private def next(): Stream[String] = queue.take match {
    case Left(0) => Stream.empty
    case Left(code) => if (StreamProcessLogger.nonzeroException) scala.sys.error("Nonzero exit code: " + code) else Stream.empty
    case Right(s) => Stream.cons(s, next())
  }
}

object StreamProcessLoggerHelp {
  def executeCommand(command: String, name: String) {
    if (name == "hive") {
      val (process, stream) = StreamProcessLogger.run(Process(Seq("hive", "-e", command)))
      stream.foreach(info => println("hive==>" + info))
    } else {
      val (process, stream) = StreamProcessLogger.run(Process(command))
      stream.foreach(info => println("info==>" + info))
    }
  }

  def main(args: Array[String]): Unit = {

    //hive的执行
//    StreamProcessLoggerHelp.executeCommand("drop table graph", "hive")

    //执行脚本,比如shell脚本,Spark脚本等
//    StreamProcessLoggerHelp.executeCommand("ls /Users/huiyu/ideaProject/graph", "shell")
    StreamProcessLoggerHelp.executeCommand("spark-shell", "shell")
  }
}

结果展示

这里写图片描述

北京小辉微信公众号

在这里插入图片描述

大数据资料分享请关注
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

北京小辉

你的鼓舞将是我最大的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值