Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run an sbt main class from the shell as normal command-line program?

How can I run an sbt app from the shell, so that I can run my app as a normal command-line program (as if run directly via scala but without having to set up an enormous classpath)?

I know I can do:

echo hello | sbt 'run-main com.foo.MyMain3 arg1 arg2' > out.txt 

But this (1) takes forever to start because it starts sbt, (2) causes all stdout and stderr to go to stdout, and (3) causes all output to be decorated with a logger [info] or [error].

I looked at https://github.com/harrah/xsbt/wiki/Launcher but it seems too heavyweight, since it downloads dependencies and sets up a new environment and whatnot. I just want to run this app within my existing development environment.

Thus far I've cobbled together my own script to build up a classpath, and you can also do some other things like modify your project file to get sbt to print the raw classpath, but I feel like there must be a better way.

like image 271
Yang Avatar asked Aug 20 '11 22:08

Yang


People also ask

How do I start Scala in CMD?

To run Scala from the command-line, download the binaries and unpack the archive. Start the Scala interpreter (aka the “REPL”) by launching scala from where it was unarchived. Start the Scala compiler by launching scalac from where it was unarchived.

How do I exit sbt shell?

To leave sbt shell, type exit or use Ctrl+D (Unix) or Ctrl+Z (Windows).


1 Answers

Here's what I have in my SBT (version 0.10) project definition,

  val Mklauncher = config("mklauncher") extend(Compile)   val mklauncher = TaskKey[Unit]("mklauncher")   val mklauncherTask = mklauncher <<= (target, fullClasspath in Runtime) map { (target, cp) =>     def writeFile(file: File, str: String) {       val writer = new PrintWriter(file)       writer.println(str)       writer.close()     }     val cpString = cp.map(_.data).mkString(":")     val launchString = """ CLASSPATH="%s" scala -usejavacp -Djava.class.path="${CLASSPATH}" "$@" """.format(cpString)     val targetFile = (target / "scala-sbt").asFile     writeFile(targetFile, launchString)     targetFile.setExecutable(true)   }    ... // remember to add mklauncherTask to Project Settings 

The mklauncher task creates a script target/scala-sbt that executes scala with the project classpath already set. It would be nice to have mklauncher executed automatically whenever the classpath changes, but I haven't looked into doing this yet.

(I use the Java classpath, rather than Scala's, for ease of creating embedded interpreters.)

like image 87
Kipton Barros Avatar answered Oct 13 '22 12:10

Kipton Barros