Scala Process - Capture Standard Out and Exit Code

You can use ProcessIO. I needed something like that in a Specs2 Test, where I had to check the exit value as well as the output of a process depending on the input on stdin (in and out are of type String):

"the operation" should {
  f"return '$out' on input '$in'" in {
    var res = ""
    val io = new ProcessIO(
      stdin  => { stdin.write(in.getBytes)
                  stdin.close() }, 
      stdout => { res = convertStreamToString(stdout)
                  stdout.close() },
      stderr => { stderr.close() })
    val proc = f"$operation $file".run(io)
    proc.exitValue() must be_==(0)
    res must be_==(out)
  }
}

I figured that might help you. In the example I am ignoring what ever comes from stderr.


You can specify an output stream that catches the text:

import sys.process._
val os   = new java.io.ByteArrayOutputStream
val code = ("volname" #> os).!
os.close()
val opt  = if (code == 0) Some(os.toString("UTF-8")) else None

I have the following utility method for running commands:

import sys.process._
def runCommand(cmd: Seq[String]): (Int, String, String) = {
  val stdoutStream = new ByteArrayOutputStream
  val stderrStream = new ByteArrayOutputStream
  val stdoutWriter = new PrintWriter(stdoutStream)
  val stderrWriter = new PrintWriter(stderrStream)
  val exitValue = cmd.!(ProcessLogger(stdoutWriter.println, stderrWriter.println))
  stdoutWriter.close()
  stderrWriter.close()
  (exitValue, stdoutStream.toString, stderrStream.toString)
}

As you can see, it captures stdout, stderr and result code.

Tags:

Scala