Scala Lift - 运行系统命令并等待完成

时间:2011-12-12 14:31:38

标签: scala cmd lift

我目前正在使用此处找到的课程:

http://www.qualitybrain.com/?p=84

一切都运行良好,但我需要代码等待命令完成然后返回一个真/假类型的响应,这样我就可以继续结果了。

我将它与OpenOffice结合使用来转换某些文档,因此在使用生成的文件之前等待文档转换完成是至关重要的。

感谢您的帮助,非常感谢:)

1 个答案:

答案 0 :(得分:1)

  1. 代码应该已经等待命令完成,因为receiveWithin是阻塞方法。您可以自行测试,只需运行示例main函数sleep 10println之前和之后。
  2. 从run函数中获取boolean结果应该非常简单,您只需要对运行函数进行一些小修改。
  3. run功能:

    def run(command:String) : Boolean = {
        println("gonna runa a command: " + Thread.currentThread)
        val args = command.split(" ")
        val processBuilder = new ProcessBuilder(args: _* )
        processBuilder.redirectErrorStream(true)
        val proc = processBuilder.start()
    
        //Send the proc to the actor, to extract the console output.
        reader ! proc
    
        //Receive the console output from the actor.
        //+========== Begin Modified Section ==============+
        //Here, we'll store the result instead of printing it, storing a None
        //if there was a timeout
    
        var commandResult : Option[String] = None
        receiveWithin(WAIT_TIME) {
            case TIMEOUT => commandResult = None
            case result:String => commandResult = Some(result)
        }
    
        //Here we interpret the result to return our boolean value
        commandResult match {
            case None => false
            case Some(s) => //... You'll have to transform the result to a true/false
                //however is most applicable to your use case
        }
    }