2014-10-03 109 views
0

如何執行需要用戶使用Scala進程交互的操作系統命令?在斯卡拉需要用戶交互的執行操作系統命令

爲了說明這一點,考慮例如passwd中的Unix/Linux操作系統,如下,

import sys.process._ 
import scala.language.postfixOps 

scala> "passwd"! 

(current) UNIX password: passwd: Authentication token manipulation error 
passwd: password unchanged 
Changing password for userabc 
res0: Int = 10 

回答

1

使用'! <'而不是'!'

"passwd"!< 

scala.sys.process.ProcessBuilder特點:

/** Starts the process represented by this builder, blocks until it exits, and 
    * returns the exit code. Standard output and error are sent to the console. 
    */ 
def ! : Int 

/** Starts the process represented by this builder, blocks until it exits, and 
    * returns the exit code. Standard output and error are sent to the console. 
    * The newly started process reads from standard input of the current process. 
    */ 
def !< : Int 
+0

'<'創建'ProcessLogger'的實例,但OP希望通過將數據發送到該進程的標準輸入與過程進行交互。 – Augusto 2014-10-04 08:03:38

1

您需要使用ProcessIO實例來處理讀取和寫入stdin /不在進程中。

def execute(command: String): Int = { 
    def reader(input: java.io.InputStream) = { 
    //read here 
    } 

    def writer(output: java.io.OutputStream) = { 
    //write here 
    } 

    val io = new ProcessIO(writer, reader, err=>err.close()) 
    Process(command).run(io).exitValue; 
} 

棘手的事情,就是你可能需要同步您的代碼寫入到流時有一些期待的投入,否則你寫的可能會迷路的字符。