I have a very simple scala program:
object TakeInputs {
def main(args: Array[String]) {
val name = readLine("What is your name?")
println(name)
}
}
When I try to run this with
sbt "project myproject" "run-main TakeInput"
it doesn't wait for user input and the program just finishes with
What is your name?null
as the output.
Is there a way to make sbt wait for user input (like what happens if "readLine" is run in sbt console)? I can provide the inputs as command line parameters but I have a lot of them and I would like to make the program more user-friendly by displaying messages indicating what the user should enter next. Thanks.
Add the following to your build.sbt
connectInput in run := true
From the sbt documentation in Configuring Input
Related
I have an Ammonite Script that I want to deliver in a JAR.
In another project I want to use this Script - but so far with no success.
I tried according to the documentation (sol_local_build.sc):
import $ivy.`mycompany:myproject_2.12:2.1.0-SNAPSHOT`, local_build
#main
def doit():Unit =
println(local_build.curl("http://localhost:8080"))
local_build.sc is in the Script I want to use.
This is the exception I get:
sol_local_build.sc:2: '.' expected but eof found.
^
The script must be compiled on the fly.
Put your script in a standard sbt project
inside a directory, example directory name: "test1"
Put your external script (example name: "script.sc")
// script.sc
println("Hello world!")
into the resource directory ("test1\src\main\resources\script.sc") of the test1 project
Publish the projekt local, i.e. sbt publishLocal
It is published to ".ivy2\local\default\test1_2.12\0.1-SNAPSHOT\ ... " directory.
Now you can use the following ammonite script "test.sc".
It reads the "script.sc" from the jar in the local ivy repository
and writes it to the local directory (must have read/write access) and then executes an external process,
which calls the scala "interpreter" and executes the script.
// test.sc
import $ivy.`default:test1_2.12:0.1-SNAPSHOT`
val scriptCode = scala.util.Try {scala.io.Source.fromResource("script.sc").mkString} getOrElse """Println("Script-file not found!")"""
println("*" * 30)
println(scriptCode)
println("*" * 30)
println()
java.nio.file.Files.write(java.nio.file.Paths.get("script.sc"), scriptCode.getBytes(java.nio.charset.StandardCharsets.UTF_8))
val cmd = Seq("cmd.exe", "/c", "scala", "script.sc")
val output = sys.process.Process(cmd).!!
println(output)
Executing the script the Ammonite REPL, you get:
******************************
// script.sc
println("Hello world!")
******************************
Hello world!
The script has no error handling and leaves the file in the running directory.
You can speed up the execution with the "-savecompiled" compiler switch, i.e
val cmd = Seq("cmd.exe", "/c", "scala", "-savecompiled", "script.sc")
An additional .jar file is created then in the running directory.
Scala Scripts are not really interpreted, but are compiled "under the hood"
as every normal Scala programm.
Therefor all code must be reachable during compile time
and you cannot call a function inside the other script from the jar-file!
But Ammonite has a buid in multi-stage feature.
It compiles one part, executes it and then compiles the next part!
Little improved ammonite-script.
It's not error free but runs.
Maybe there is better way to get the script out of the jar.
You should ask Li Haoyi!
// test_ammo.sc
// using ammonite ops
// in subdirectoy /test1
// Ammonite REPL:
// import $exec.test1.test_ammo
// # Ammonite-multi-stage
import $ivy.`default::test1:0.1-SNAPSHOT`
//import scala.util.Properties
import scala.sys.process.Process
val scriptFileName = "script.sc"
write.over(pwd/"test1"/scriptFileName, read(resource(getClass.getClassLoader)/scriptFileName))
val cmd = Seq("cmd.exe", "/c", "scala", scriptFileName)
val output = Process(cmd).!!
println(output)
#
import $exec.script // no .sc suffix
ppp() // is a function inside script.sc
script.sc inside resources folder of project
published local with "sbt publishLocal":
// script.sc
println("Hello world!")
def ppp() = println("Hello world from ppp!")
For completeness, I could solve my problem as follows:
Just create a Scala File in this project.
Copy the Script content in
an Object.
package mycompany.myproject
object LocalBuild {
def curl(..)...
}
Add the dependencies to your sbt file (e.g. ammonite.ops)
Use it like:
$ivy.`mycompany:myproject_2.12:2.1.0-SNAPSHOT`, mycompany.myproject.LocalBuild
#main
def doit():Unit =
println(LocalBuild.curl("http://localhost:8080"))
I have the following scala program that simply counts the words in a file:
package com.impatient
import java.util.Scanner
object Main extends App {
countWords()
def countWords(): Unit = {
val in = new Scanner(new java.io.File("C:\\tmp\\SampleText.txt"))
var wc = 0
while (in.hasNext()) {
var word = in.next()
wc += 1
println( wc + ". " + word)
}
in.close()
println("======================")
println(s"Total words: $wc")
}
def TestFunction(): Unit ={
println("Hello from test function!")
}
TestFunction()
}
When I execute this in intellij, either directly or via the sbt shell inside intellij, I get the following output:
mostly
positive:
======================
Total words: 309
Hello from test function!
So it correctly counts 309 words in the text file.
However if I try to execute the jar that I just compiled with intellij, directly, either via scala or sbt I get the following output:
λ scala .\impatientscala2_2.12-1.0.jar
======================
Total words: 0
Hello from test function!
So in this case, although the methods in Main are executed the wordcount is 0.
Why would be this the case? Is intellij referencing some other java libraries that standalone sbt or scala isn't? In that case why doesn't the Scanner fail?
Edit 1
I have cloned this repo to another PC to see what happens. And in that case I can observe the exact opposite, i.e.:
The program returns 0 word count when run from Intellij
When the jar is run directly with scala, it gives the current wordcount.
The 0 wordcount is due to not processing the while loop, as in.hasNext() returns nothing.
I found a workaround by using Paths.get from java.nio.file._.
//val in = new Scanner(new java.io.File("C:/tmp/SampleText.txt"))
val in: Scanner = new Scanner(Paths.get("C/tmp/SampleText.txt"))
This produces the correct jars on both PCs, when using Run | Sbt Task in Intellij, using SBT Shell in intellij, and using standalone SBT shell. If anyone can provide an explanation of why would java.io.File fail in certain setups that would be great.
My tests are slow. Real slow. Like I can get another cup of coffee and reading some articles while waiting for them to finished slow. So I added this task to build.sbt just to alert me when my testing is finished.
lazy val alertMe = taskKey[Unit]("Alert me when testing is completed.")
alertMe in Test := {
"say \"testing is completed\""!
}
Noted that I use say command on OS X. I then used this task like this.
;test ;alertMe
Voila! This works great.... only for successful testing. In case that any test case failed, test task return result as error, and alertMe is not invoked.
This behavior is pretty understandable. but I want my task, alert me, to run regardless of test task result. How can I do this ?
Maybe you can add test task in alertMe task, like:
lazy val alertMe = taskKey[Unit]("Alert me when testing is completed.")
alertMe := {
Command.process("test", state.value)
"say \"testing is completed\""!
}
usage: sbt alertme, it will run the test task and the shell command.
Command.process will execute the test task and without causing current task fail. so the commands always will be executed.
I am trying to write a simple console client application where i can present some options to the user, get their input and act accordingly. If i run the code through intellij or paste it into the scala console, it works. If i run it through sbt (which is how i really need it to run), i run into all sorts of problems.
I have sbt version 0.13.8, OS is Mac, my build.sbt contains:
scalaVersion := "2.11.6"
fork in run := true
EDIT I started with the minimum scala activator template in case that is useful info in this context
I have simplified the code to barebones,
import scala.io.StdIn._
object TestClient {
def main(args: Array[String]): Unit = {
join()
}
def join(): Unit = {
val name = readLine(s"Enter your name.${System.getProperty("line.separator")}")
name match {
case n: String => println(n)
case o => {
println(s"invalid name ${o}")
join()
};
}
}
}
When go into sbt and from the prompt enter run. one of the following seems to happen
1) I get this exception as soon as i run
Exception in thread "Thread-2" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3332)
at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:137)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:121)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:569)
at java.lang.StringBuffer.append(StringBuffer.java:369)
at java.io.BufferedReader.readLine(BufferedReader.java:370)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at sbt.BasicIO$$anonfun$processFully$1$$anonfun$apply$8.apply(ProcessImpl.scala:58)
at sbt.BasicIO$$anonfun$processFully$1$$anonfun$apply$8.apply(ProcessImpl.scala:58)
at sbt.BasicIO$.readFully$1(ProcessImpl.scala:63)
at sbt.BasicIO$.processLinesFully(ProcessImpl.scala:69)
at sbt.BasicIO$$anonfun$processFully$1.apply(ProcessImpl.scala:58)
at sbt.BasicIO$$anonfun$processFully$1.apply(ProcessImpl.scala:55)
at sbt.SimpleProcessBuilder$$anonfun$3.apply$mcV$sp(ProcessImpl.scala:354)
at sbt.Spawn$$anon$3.run(ProcessImpl.scala:17)
2)
No memory issues, but getting these messages in an infinite loop, so the readline does not seem to be waiting for any input
background log: info: Enter your name.
background log: info: invalid name null
background log: info: Enter your name.
background log: info: invalid name null
...
Either way I am unable to actually enter any input in the console. Not sure what I'm missing or doing wrong
Put
connectInput in run := true
in your build.sbt. See the official docs for more info on how to correctly handle forks in sbt.
I want use Scala like Python, so I install REPL in Sublime Text(Os is win8)
Everytime in REPL, I have to
scala> :load <my file>
, so I think it's inconvenient.
And I can't change
scala> :settings -d <路径名>
in Chinese directory.
I'm confused whether I can't change Scala script's directory with non-english language.
Thanks a lot!
If you use sbt then you can define initial commands when you launch the console.
yourproject/build.sbt:
// build.sbt
name := "initial-commands-example"
initialCommands := "import Foo._"
yourproject/script.scala:
// script.scala
object Foo {
def hello(name: String) = s"hello $name"
val msg = hello("world")
}
Inside yourproject, run sbt console, and you will have everything in Foo available inside that repl. See sbt initialCommands docs for more information.