2012-08-08 151 views
9

是否有熱鍵來停止/退出Scala REPL?熱鍵停止REPL?

示例:我使用命令console從SBT啓動Scala REPL,然後像無盡循環那樣做一些愚蠢的事情,並且希望在不關閉shell的情況下結束REPL。喜歡的東西按Ctrl +Ç按Ctrl +d按Ctrl +ž(所有不工作)。

更新: 使用操作系統:Windows 7 64位。

按Ctrl + d存在SBT和REPL,但按Ctrl + d當我在一個死循環一樣

while(true) prinln("test") 

不退出REPL有沒有一種辦法用熱鍵離開無限循環而不關閉殼體?或者這是不可能的,因爲在循環完成之前REPL不會對熱鍵作出反應(當然,這種情況在這種情況下不會發生)?

+0

hm您使用的操作系統是什麼?因爲ctrl + c似乎對我有用(在MacOS 10.6下) – 2012-08-08 21:32:04

+0

是從sbt啓動的,因爲你說'console'? – 2012-08-08 21:35:10

+0

@MateuszDymczyk哦,我明白了,這似乎是一個操作系統特定的問題。我使用Windows 7 64位版本。 Ctrl + C不適用於我。 – 2012-08-08 21:35:45

回答

2

以下工作適用於Scala 2.10.0-M6,但在2.9.2中,您可以在REPL電源模式下使用:wrap實現類似的功能。

假設REPL是通過sbt console —從sbt開始的,而不失一般性(否則可以將ReplUtil類放在scala的類路徑上)。假設以下班級在班級路徑上,例如其源處於src/main/scala/ReplUtil.scala

import java.util.concurrent.{Executors, ExecutorService, TimeoutException, TimeUnit} 
import concurrent._ 

object ReplUtil { 
    @volatile private var exec: ExecutorService = _ 
    @volatile private var threads = Set.empty[ Thread ] 
    private def freshPool() { exec = Executors.newCachedThreadPool() } 
    freshPool() 

    private implicit def context = ExecutionContext.fromExecutorService(exec) 

    def panic() { 
    (new Thread { 
     override def run() { 
     try { 
      exec.shutdownNow() 
      exec.awaitTermination(1, TimeUnit.SECONDS) 
     } finally { 
      val th = threads 
      threads = Set.empty 
      th.foreach(_.stop) 
      freshPool() 
     } 
     } 
    }).start() 
    }  

    def spawn[T](t: => T) = { 
    var futPrint = false 
    val fut = future { 
     val th = Thread.currentThread() 
     threads += th 
     val res = try { t } finally { threads -= th } 
     if(futPrint) println("<calculation done>\n" + res) 
     t 
    } 
    try { 
     Await.result(fut, util.Duration(4, TimeUnit.SECONDS)).toString 
    } catch { 
     case e: TimeoutException => 
     futPrint = true 
     "<ongoing calculation>" 
    } 
    } 
} 

那麼下面將激活半異步REPL:

$ sbt console 
... 
Welcome to Scala version 2.10.0-M6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_33). 
... 
scala> import ReplUtil.panic 
import ReplUtil.panic 

scala> :power 
** Power User mode enabled - BEEP WHIR GYVE ** 
... 

scala> power.intp.setExecutionWrapper("ReplUtil.spawn") 

scala> 2+2 
res1: Int = 4 

scala> Thread.sleep(6000); 33 
<ongoing calculation> 

scala> <calculation done> 
res2: Int = 33 

scala> while(true) { Thread.sleep(2000); println("Zzz")} 
Zzz 
Zzz 
<ongoing calculation> 
scala> panic 

scala> [error] (pool-5-thread-1) java.lang.ExceptionInInitializerError 
java.lang.ExceptionInInitializerError 
... 
Caused by: java.lang.InterruptedException: sleep interrupted 
... 
+0

當A是+0時Q怎麼可以是+6?無論如何,鑑於wrap的消亡,REPL需要通用的模板,內置了「timed」,「interruptible」等。 – 2014-05-14 07:18:18

0

與主題相關的是一個有用的移位 + d鍵用於退出非結合在eclipse scala工作表中終止對程序的評估。