如何在 Scala 中 运行 外部进程并获得退出代码和输出?

How to run external process in Scala and get both exit code and output?

如何在完成后调用外部进程并读取其退出代码和标准输出?

使用 sys.Process 将导致在不同于 0 的退出代码上抛出异常。

你看过Process.exitValue了吗?

Returns the exit value for the subprocess.

(我在 freenode #java 上问过这个问题,如果我找到了解决方案,我会被要求 post 在这里)

简单的方法是使用 sys.ProcessBuilder:

  def RunExternal(executableName: String, executableDir: String) : (Int, List[String]) = {
    val startExecutionTime = System.currentTimeMillis()

    val pb : ProcessBuilder = new ProcessBuilder (executableName)
    pb.directory(new java.io.File(executableDir))

    val proc = pb.start()
    proc.waitFor()

    val exitCode = proc.exitValue()
    val output = scala.io.Source.fromInputStream(proc.getInputStream).getLines.toList

    val executionTime = System.currentTimeMillis() - startExecutionTime

    logger.info(String.format(s"Process exited with exit code: ${exitCode}."))
    logger.info(String.format(s"Process took ${executionTime} milliseconds."))

    (exitCode, output)
  }

试试这个:

import sys.process._

val stdout = new StringBuilder
val stderr = new StringBuilder
val logger = ProcessLogger(stdout append _, stderr append _)
val status = "ls -al " ! logger

println(status)
println("stdout: " + stdout)
println("stderr: " + stderr)

然后你得到了它们:status、stdout 和 stderr。