【问题标题】:How to add imports to REPL from command line?如何从命令行向 REPL 添加导入?
【发布时间】:2013-08-29 10:59:28
【问题描述】:

如何让 REPL 导入命令行中给出的包?

示例:

scala -someMagicHere "import sys.error"
scala> :imports
1) import scala.Predef._          (162 terms, 78 are implicit)
2) import sys.error               (2 terms)

scala> _

PS:它不是重复的。我想要自动化解决方案,而不是每次运行 REPL 时手动粘贴一些代码。另外,我不想使用 SBT 仅在 REPL 启动后运行一个命令。

【问题讨论】:

标签: scala read-eval-print-loop


【解决方案1】:

把它粘在一个文件里。

apm@mara:~/tmp$ scala -i imports.script
Loading imports.script...
import sys.error

Welcome to Scala version 2.10.2 (OpenJDK 64-Bit Server VM, Java 1.7.0_25).
Type in expressions to have them evaluated.
Type :help for more information.

scala> :impo
 1) import scala.Predef._          (162 terms, 78 are implicit)
 2) import sys.error               (2 terms)

编辑:

我认为你会因发现或以其他方式引发或诱导错误而获得奖励积分:

apm@mara:~/tmp$ scala -e "import sys.error"
java.lang.ClassNotFoundException: Main

【讨论】:

    【解决方案2】:

    我写了一个脚本来自动化命令行参数到文件的事情(基于来自som-snytt的A)。它在 win 7 上使用MSYS 进行了测试,但它应该也可以在 Linux 上运行。

    bash-3.1$ repl "import sys.error"
    Loading C:\Users\xxx\AppData\Local\Temp\tmp.GgEjauEqwz...
    import sys.error
    
    Welcome to Scala version 2.10.0 (Java HotSpot(TM) Client VM, Java 1.7.0_07).
    Type in expressions to have them evaluated.
    Type :help for more information.
    scala> :impo
     1) import scala.Predef._ (162 terms, 78 are implicit)
     2) import sys.error (2 terms)
    
    #!/bin/bash
    
    function crash {
        echo "Error: $1"
        exit 10
    }
    
    if [ $# -ne 1 ]; then
        echo "Script requires one parameter."
        exit 1
    fi
    
    t=$(mktemp) || crash "Unable to create a temp file."
    [ ${#t} -lt 1 ] && crash "Suspiciously short file name, aborting."
    trap "rm -f -- '$t'" EXIT
    
    echo "$1" > "$t"
    scala -i "$t" || crash "Something wrong with scala binary."
    
    rm -f -- "$t"
    trap - EXIT
    exit
    

    【讨论】:

    • 我不了解 SO 工作流程,看来您建议在我的答案中保留此内容,而有些人说不,您不能这样做吗?无论如何,我看到你想提供进口。我想更多的是,reflection-imports.script 包含繁琐的 import reflect.runtime 等,而 scala -i 的别名使其方便。我想我可以看到你的想法的一个用例,你提供一个包,它可以从中导入所有东西。 concurrent._, duration._ 是另一个烦恼。顺便说一句,你知道是时候升级你的 scala 和 java 了吗?
    • @som-snytt 是的,我只想编辑你的答案并接受它,但我的编辑被拒绝了:(。我使用它的确切原因是你写的 - 导入所有带下划线的东西.(我不知何故破坏了java自动升级的东西,看起来我错过了很多更新,我会手动做的。)谢谢你的帮助:)。
    • 如何使用所有参数,for arg in $* ; do echo "$arg" >> $f ; done 或类似的。
    • @som-snytt 这是一个选项。但它已经支持多个命令,而且更短:repl "import a.b.c; import d.e.f" vs. repl "import a.b.c" "import d.e.f"
    猜你喜欢
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2015-04-20
    • 2019-12-04
    • 2012-04-10
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多