Executing shell commands from Scala REPL

后端 未结 5 1980
礼貌的吻别
礼貌的吻别 2021-01-01 20:44

An interesting feature of Scala REPL is if you drop any jar in your %SCALA_HOME%\\lib directory, it is available for import from the REPL. I have several jars t

5条回答
  •  心在旅途
    2021-01-01 21:20

    UPDATE 2018/01/15

    Example: you like to see the files in the current working directory:

    scala> :sh ls -l
    res3: scala.tools.nsc.interpreter.ProcessResult = `ls -l` (13 lines, exit 0)
    

    But you can't do this:

    scala> res3.foreach {println}
    :40: error: value foreach is not a member of scala.tools.nsc.interpreter.ProcessResult
           res3.foreach {println}
                ^
    

    First you have to assign the lines to another type that supports iteration:

    scala> res3.lines
    res7: List[String] = List(total 960, -rw-r--r--@  1 dave  staff   11325 Jan  3 15:01 LICENSE, -rw-r--r--@  1 dave  staff    8859 Jan  3 15:01 README.rst, drwxr-xr-x@  3 dave  staff      96 Jan  3 15:03 assembly, drwxr-xr-x@ 20 dave  staff     640 Jan  3 15:01 bin, drwxr-xr-x@ 13 dave  staff     416 Jan  3 15:01 doc, drwxr-xr-x@  7 dave  staff     224 Jan  3 15:01 docker, drwxr-xr-x@  6 dave  staff     192 Jan  3 15:03 examples, -rw-r--r--@  1 dave  staff     826 Jan  3 15:01 gradle.properties, -rw-r--r--@  1 dave  staff     128 Jan  3 15:04 h2o_drivers.txt, drwxr-xr-x   3 dave  staff      96 Jan 16 00:54 h2ologs, drwxr-xr-x@  5 dave  staff     160 Jan  3 15:04 py, -rw-r--r--@  1 dave  staff  455890 Sep 19 04:18 rsparkling.tar.gz)
    

    Then iterate, and voila!

    scala> res7.foreach {println}
    total 960
    -rw-r--r--@  1 dave  staff   11325 Jan  3 15:01 LICENSE
    -rw-r--r--@  1 dave  staff    8859 Jan  3 15:01 README.rst
    drwxr-xr-x@  3 dave  staff      96 Jan  3 15:03 assembly
    drwxr-xr-x@ 20 dave  staff     640 Jan  3 15:01 bin
    drwxr-xr-x@ 13 dave  staff     416 Jan  3 15:01 doc
    drwxr-xr-x@  7 dave  staff     224 Jan  3 15:01 docker
    drwxr-xr-x@  6 dave  staff     192 Jan  3 15:03 examples
    -rw-r--r--@  1 dave  staff     826 Jan  3 15:01 gradle.properties
    -rw-r--r--@  1 dave  staff     128 Jan  3 15:04 h2o_drivers.txt
    drwxr-xr-x   3 dave  staff      96 Jan 16 00:54 h2ologs
    drwxr-xr-x@  5 dave  staff     160 Jan  3 15:04 py
    -rw-r--r--@  1 dave  staff  455890 Sep 19 04:18 rsparkling.tar.gz
    

提交回复
热议问题