2015-11-06 76 views
0

比方說,我有一個命令,我需要從斯卡拉運行:如何重定向輸出*和*使用Scala Process/ProcessBuilder設置CWD和ENV?

program -i inputFile 

我可以調用這個使用捕捉文件中的輸出在斯卡拉:

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在我的環境,運行程序,捕獲輸出到文件。我怎麼做?

回答

1

您需要使用中間ProcessBuilder而不是您首先嚐試的DSL。此外,ProcessLogger類用於映射輸出。所以,

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

然後等待它完成。您還可以提供流式作家等。

+0

謝謝。這大多工作。我說主要是因爲捕獲的輸出是4415488字節,應該是4424370.就好像輸出緩衝區的最終刷新從未發生過。我檢查了'val status:Int = runningCommand.exitValue()'後返回0。 – gknauth

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()