Search code examples
scalaprocessexternal

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


How to call an external process and read both of its exit code and standard out, once it finished?

Using sys.Process will result in an exception being thrown on different exit code than 0 for success.


Solution

  • Try this:

    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)
    

    Then you got both of them: status, stdout and stderr.