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 there, and I often need to find out which ones are available to be included. So I always have to open another command window and find out which jars exist in that directory. It would be great if the REPL allowed me to execute system commands such as dir
or ls
or at least list all the jars in the above lib directory. What is the easiest way (if any) to invoke shell commands in REPL ?
We can start Scala REPL by typing scala command in console/terminal. Let's understand how we can add two variable using Scala REPL. In first line we initialized two variable in Scala REPL. Then Scala REPL printed these.
Go to the Apache Spark Installation directory from the command line and type bin/spark-shell and press enter, this launches Spark shell and gives you a scala prompt to interact with Spark in scala language. If you have set the Spark in a PATH then just enter spark-shell in command line or terminal (mac users).
In REPL the :sh
command allow you to introduce shell command:
Windows version:
scala> :sh cmd /C dir
res0: scala.tools.nsc.interpreter.ProcessResult = `cmd /C dir` (28 lines, exit 0)
scala> res0 foreach println
(unfortunately, there is no way to avoid the call to cmd \C
before the shell command)
Unix-like version:
scala> :sh ls
res0: scala.tools.nsc.interpreter.ProcessResult = `cmd /C dir` (28 lines, exit 0)
scala> res0 foreach println
Update: Inspired by Daniel's answer, a little trick for windows user:
scala> implicit def stringToDosProcess(s: String) =
scala.sys.process.stringToProcess("cmd /C "+ s)
stringToDosProcess: (s: String)scala.sys.process.ProcessBuilder
scala> "dir".!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With