Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Process - Capture Standard Out and Exit Code

Tags:

scala

I'm working with the Scala scala.sys.process library.

I know that I can capture the exit code with ! and the output with !! but what if I want to capture both?

I've seen this answer https://stackoverflow.com/a/6013932/416338 which looks promising, but I'm wondering if there is a one liner and I'm missing something.

like image 921
Nick Long Avatar asked Mar 14 '13 14:03

Nick Long


1 Answers

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.

like image 124
Rogach Avatar answered Sep 18 '22 01:09

Rogach