gpt4 book ai didi

scala - 停止REPL的热键?

转载 作者:行者123 更新时间:2023-12-04 04:35:37 25 4
gpt4 key购买 nike

是否有热键停止/退出Scala REPL?

示例:我使用console命令从SBT启动Scala REPL,然后做一些无穷循环之类的愚蠢操作,并希望完全不关闭 shell 而结束REPL。诸如Ctrl + C,Ctrl + D或Ctrl + Z之类的东西(均不起作用)。

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

Ctrl + D存在SBT和REPL,但是当我处于无休止的循环中时,Ctrl + D不会退出REPL

while(true) prinln("test")

有没有办法在不关闭 shell 的情况下通过热键退出无休止的循环?还是因为REPL在循环通过之前不会对热键作出 react (这在这种情况下当然不会发生)是不可能的吗?

最佳答案

以下内容适用于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
...

关于scala - 停止REPL的热键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11873380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com