Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing shell commands from Scala REPL

Tags:

scala

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 ?

like image 600
Jus12 Avatar asked Mar 27 '12 08:03

Jus12


People also ask

How do I run a scala code 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.

How do I call a shell script from spark?

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).


1 Answers

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".!
like image 80
Nicolas Avatar answered Sep 28 '22 13:09

Nicolas