Run Scala application on different process - scala

Hi I want to create a program that starts another application on a new process:
object A{
def main(args: Array[String]) {
Process(????).run
println("new process has been created")
}
}
the application that should run on the new process:
object B{
def main(args: Array[String]) {
print("Hello world")
}
}
I know I can run a script using Process(script_string_to_run), but I don't know how to make it run another application..

Run Scala program from another Scala program
Scala Program
B.scala
object B {
def main(args: Array[String]): Unit = println("hello world")
}
Now execute the above program like this from another Scala program.
scala> import sys.process._
import sys.process._
scala> "scala B.scala" !!
warning: there was one feature warning; re-run with -feature for details
res1: String =
"hello world
"
Note that the file name of the file is same as the object name containing main method. This way scala would recognise the main class/object and execute the main method of the program. If the name of the file is not the name of the object containing the main method then It would not know what to execute.
! gives the exit status of the program after execution whereas !! gives the output of the program.
scala> import sys.process._
import sys.process._
scala> val status = "scala B.scala" !
warning: there was one feature warning; re-run with -feature for details
hello world
status: Int = 0
scala> val output = "scala B.scala" !!
warning: there was one feature warning; re-run with -feature for details
output: String =
"hello world
Scala Script
Test.sh
#!/usr/bin/env scala
object B{
def main(args: Array[String]) {
print("Hello world")
}
}
B.main(Array[String]())
Now Just run the B program using
"./Test.sh" !!
Command Line Activity
➜ cd demo
➜ demo ./Test.sh
zsh: permission denied: ./Test.sh
➜ demo chmod +rwx Test.sh
➜ demo ./Test.sh
Hello world%
➜ demo ./Test.sh
Hello world%
➜ demo scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_45).
Type in expressions for evaluation. Or try :help.
scala> import sys.process._
import sys.process._
scala> "./Test.sh" !!
warning: there was one feature warning; re-run with -feature for details
res0: String =
"Hello world
"
scala> :q

Related

How to execute a Scala3 script when system has both Scala2 and Scala3 installed?

I want to execute a following script using Scala3:
#main def m() =
println("Hello, world! I'm a script")
When I type the command, scala hello.scala, I get the following error:
/Users/avirals/dev/learning-scala/hello-world/hello.scala:1: error: not found: type main
#main def m() =
^
one error found
I think it is because I have both the versions of Scala installed (2 and 3). I know how to start a REPL for both (as mentioned here) but I am not able to execute a Scala3 script from the command line.
[Update]
I tried scala3-repl hello.scala and it just opens the REPL:
➜ learning-scala git:(main) scala3-repl hello.scala
scala> m()
1 |m()
|^
|Not found: m
How do I execute a Scala 3 script from the command line given I have two different versions (2 and 3) of Scala installed?
My OS: MacOS
Update 2
As suggested in this answer, I tried running with amm and it worked for a few scripts. However, the following script failed:
Script:
#main def m(args: String*) =
var i = 0
while i < args.length do
println(args(i))
i += 1
Error:
➜ learning-scala git:(main) amm printargs.scala
printargs.scala:2:3 expected (If | While | Try | DoWhile | For | Throw | Return | ImplicitLambda | SmallerExprOrLambda)
var i = 0
^
Running the above script in a Scala3-REPL works:
➜ learning-scala git:(main) scala3-repl
scala> #main def m(args: String*) =
| var i = 0
| while i < args.length do
| println(args(i))
| i += 1
|
def m(args: String*): Unit
scala> m("aviral", "srivastava")
aviral
srivastava
Running the same script in a system (MacOS) that has only Scala3 installed works just fine as well.
There exists currently Minimal scripting support #11379. I was able to get it working by manually downloading a release from https://github.com/lampepfl/dotty/releases/download/3.0.0-RC3/scala3-3.0.0-RC3.zip, unzipping, and giving executable permission to launchers
./scala3-3.0.0-RC3/bin/scala hello.scala
Hello, world! I'm a script
With scala3-repl launcher you could at least do
$ scala3-repl
scala> :load hello.scala
def m(): Unit
scala> m()
Hello, world! I'm a script

Print on Scala in Intellij and in ScalaFiddle

I am new in Scala. I try to repeat code from scaladocs.
I write
println(1 + 1)
and i cant run it.
But in ScalaFiddle (https://scalafiddle.io/) it works.
In other tutorial, i have to write
object ScalaApp{
def main(args: Array[String]): Unit = {
println(1 + 1)
}
}
and it works for me in Intellij.
What the difference?
Did you install IntelliJ's scala plugin?
If not, steps are detailled here : https://www.jetbrains.com/help/idea/run-debug-and-test-scala.html
On Unix you can also run simple scala programs using a shabang. For example with your code in test.sh you can
bash-3.2$ cat test.sh
#!/usr/bin/env scala
object ScalaApp{
def main(args: Array[String]): Unit = {
println(1 + 1)
}
}
bash-3.2$ chmod +x test.sh
bash-3.2$ ./test.sh
2

how to import a class in scala

I am learning scala recently, the package in scala confused me.
I have a file named StockPriceFinder.scala:
// StockPriceFinder.scala
object StockPriceFinder {
def getTickersAndUnits() = {
val stockAndUnitsXML = scala.xml.XML.load("stocks.xml")
(Map[String, Int]() /: (stocksAndUnitsXML \ "symbol")) {
(map, symbolNode) =>
val ticker = (symbolNode \ "#ticker").toString
val units = (symbolNode \ "units").text.toInt
map ++ Map(ticker -> units)
}
}
}
then I want to use StockPriceFinder in test.scala which is in the same folder:
val symbolAndUnits = StockPriceFinder.getTickersAndUnits
but when I run it with scala test.scala, I got error:error: not found: value StockPriceFinder. In Java, if this two source files are in the same folder, I do not need to import and I can use it directly, so how can I import StockPriceFinder correctly in scala?
I have tried to use import StockPriceFinder in test.scala, but it still does not work.
You don't need to import StockPriceFinder if the files are in the same package (not folder).
But you do need to compile StockPriceFinder.scala first and pass the correct classpath to scala.
scalac StockPriceFinder.scala
scala -cp . test.scala
should work (might be a bit off). However, you shouldn't do it manually, since it becomes unmanageable very quickly; use SBT or other build tools (Maven, Gradle).

Scala Presentation Compiler

Hi I've been trying to get the presentation compiler to work but I'm getting the following error. Any help regarding this would be appreciated. I've already seen other questions and few projects where it has been implemented but everyone uses the Global.Run which is not being recognized in the REPL. This the code and the error below it. I've installed scala 2.10.3 in windows 8.1
import scala.tools.nsc.{Global,Settings}
import scala.tools.nsc.reporters._
object Test {
def main (args: Array[String]) {
val settings = new Settings;
val global = new Global(settings,new ConsoleReporter(settings));
val compiler = global.Run;
}
}
The error is
Sample.scala:8: error: value Run is not a member of scala.tools.nsc.Global
Try this:
import scala.tools.nsc.{Global,Settings}
import scala.tools.nsc.reporters._
object Test {
def main (args: Array[String]) {
val settings = new Settings
val global = new Global(settings,new ConsoleReporter(settings))
val compiler = new global.Run
}
}
Notice new Run instead of Run. There is no companion object for class Run. Maybe it was there before in earlier scala versions. Checked on Scala v2.10.3. Works in REPL.

error of run scala code

I have the following code:
package db
import com.mongodb.casbah.{ MongoCollection, MongoConnection, MongoDB }
import com.mongodb.casbah.commons.{ MongoDBObject }
object Test {
def main(argc: Array[String]) {
val db = MongoDB(MongoConnection(), "test")
val objText = MongoDBObject("user" -> "This the text is test number the two")
val coll = db.getCollection("coll_tet")
coll.insert(objText)
print(coll.find())
}
}
And I do scalac -classpath ... test.scala
When I tried to run this: scala db.Test -classpath ... I'm get an error:
Exception in thread "main" java.lang.NoClassDefFoundError: com/mongodb/Mongo
Why is this happening?
Why don't you just add the Imports object?
import com.mongodb.casbah.Imports._
And it should take care of all your import problems.