假设我需要从Scala运行命令:
program -i inputFile
我可以调用它并使用以下方法在Scala中的文件中捕获输出:
val command = Seq("program", "-i", "inputFile")
val status = (command #> new File("capturedOutput")).!
但我也需要设置环境和当前工作目录。 这有效:
val env = "KEY" -> "value"
val dir = new File("desiredWorkingDir")
val status = Process(command, dir, env).!
但我不知道怎么把它们放在一起,也就是说,在我的环境中设置env,在某个目录中运行程序,和捕获文件中的输出。我该怎么做?
答案 0 :(得分:1)
您需要使用中间ProcessBuilder
而不是您最初尝试过的DSL。此外,用于映射输出的ProcessLogger
类。所以,
val pb: ProcessBuilder = Process(command, dir, env)
val runningCommand = pb.run(ProcessLogger(new File("capturedOutput")))
然后等待它完成。您还可以提供流编写器等。
答案 1 :(得分:0)
如果我接受,这是@ bob-dalgleish答案的扩展。我遇到的问题是ProcessLogger捕获了大部分但不是所有的输出。 如果我在获取进程的exitValue后关闭了processLogger,我得到了所有的输出。这是完整的代码:
val outputFilename = "capturedOutput-" + timestamp + ".txt"
val outputPath = dirForOutputFile + "/" + outputFilename
var env = "Key" -> "Value"
val dir: File = new File("desiredWorkingDir")
val command = Seq("program", "-i", "inputFile")
val pb: ProcessBuilder = Process(command, dir, env)
val processLogger = new FileProcessLogger(new File(outputPath))
val runningCommand = pb.run(processLogger)
val status: Int = runningCommand.exitValue()
processLogger.close()