Search code examples
scalaprocessbuilder

How I redirect output *and* set the CWD & ENV using Scala Process / ProcessBuilder?


Let's say I have a command I need to run from Scala:

program -i inputFile

I can invoke this and capture the output in a file in Scala using:

val command = Seq("program", "-i", "inputFile")
val status = (command #> new File("capturedOutput")).!

But I need to set the environment and current working directory too. This works:

val env = "KEY" -> "value"
val dir = new File("desiredWorkingDir")
val status = Process(command, dir, env).!

but I don't know how to put it all together, that is, to set env in my environment, run program in a certain directory, and capture the output in a file. How do I do that?


Solution

  • You need to use the intermediate ProcessBuilder instead of the DSL you tried at first. Also, the ProcessLogger class that is used for mapping outputs. So,

    val pb: ProcessBuilder = Process(command, dir, env)
    val runningCommand = pb.run(ProcessLogger(new File("capturedOutput")))
    

    then wait for it to be done. You can also provide stream writers, etc.