已复制
全屏展示
复制代码

Scala调用并执行外部Linux命令

· 1 min read

Scala 执行命令非常简单,不需要额外的依赖。

package org.example

import scala.collection.mutable
import scala.sys.process.{Process, ProcessLogger}

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

    // Execute the command and capture the exit code, stdout, and stderr
    val cmd = "cat /etc/profile | wc -l"
    val stdoutStr = new mutable.StringBuilder
    val stderrStr = new mutable.StringBuilder
    var exitCode = 0
    var stdout = ""
    var stderr = ""

    try {
      exitCode = Process(Seq("bash", "-c", cmd))
        .!(ProcessLogger(stdoutStr.append(_), stderrStr.append(_)))
      stdout = stdoutStr.toString
      stderr = stderrStr.toString
    } catch {
      case ex: Exception =>
        exitCode = -1
        stderr = ex.getMessage
    }

    println("exitCode: " + exitCode)
    println("stdout: " + stdout)
    println("stderr: " + stderr)
  }
}

执行结果

exitCode: 0
stdout: 76
stderr: 
🔗

文章推荐