在Scala中执行需要用户交互的OS命令

时间:2014-10-03 17:39:39

标签: linux scala unix process user-interaction

如何使用Scala进程执行需要用户交互的操作系统命令?

为了说明这一点,请考虑例如Unix / Linux OS中的passwd,如下所示,

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

2 个答案:

答案 0 :(得分:1)

您需要使用ProcessIO实例来处理读取和写入stdin / out的过程。

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;
}

有些棘手的问题是,当有需要输入的内容时,您可能需要同步代码以写入流,否则您编写的字符可能会丢失。

答案 1 :(得分: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