How does the “scala.sys.process” from Scala 2.9 work?

Scala

Scala Problem Overview


I just had a look at the new scala.sys and scala.sys.process packages to see if there is something helpful here. However, I am at a complete loss.

Has anybody got an example on how to actually start a process?

And, which is most interesting for me: Can you detach processes?

A detached process will continue to run when the parent process ends and is one of the weak spots of Ant.

UPDATE:

There seem to be some confusion what detach is. Have a real live example from my current project. Once with z-Shell and once with TakeCommand:

Z-Shell:

if ! ztcp localhost 5554; then
    echo "[ZSH] Start emulator"
    emulator						\
	-avd    Nexus-One				\
	-no-boot-anim					\
	1>~/Library/Logs/${PROJECT_NAME}-${0:t:r}.out	\
	2>~/Library/Logs/${PROJECT_NAME}-${0:t:r}.err	&
    disown
else
    ztcp -c "${REPLY}"
fi;

Take-Command:

IFF %@Connect[localhost 5554] lt 0 THEN
   ECHO [TCC] Start emulator
   DETACH emulator -avd Nexus-One -no-boot-anim
ENDIFF

In both cases it is fire and forget, the emulator is started and will continue to run even after the script has ended. Of course having to write the scripts twice is a waste. So I look into Scala now for unified process handling without cygwin or xml syntax.

Scala Solutions


Solution 1 - Scala

First import:

import scala.sys.process.Process

then create a ProcessBuilder

val pb = Process("""ipconfig.exe""")

Then you have two options:

  1. run and block until the process exits

    val exitCode = pb.!
    
  2. run the process in background (detached) and get a Process instance

    val p = pb.run
    

    Then you can get the exitcode from the process with (If the process is still running it blocks until it exits)

    val exitCode = p.exitValue
    

If you want to handle the input and output of the process you can use ProcessIO:

import scala.sys.process.ProcessIO
val pio = new ProcessIO(_ => (),
                        stdout => scala.io.Source.fromInputStream(stdout)
                          .getLines.foreach(println),
                        _ => ())
pb.run(pio)

Solution 2 - Scala

I'm pretty sure detached processes work just fine, considering that you have to explicitly wait for it to exit, and you need to use threads to babysit the stdout and stderr. This is pretty basic, but it's what I've been using:

/** Run a command, collecting the stdout, stderr and exit status */
def run(in: String): (List[String], List[String], Int) = {
  val qb = Process(in)
  var out = List[String]()
  var err = List[String]()

  val exit = qb ! ProcessLogger((s) => out ::= s, (s) => err ::= s)

  (out.reverse, err.reverse, exit)
}

Solution 3 - Scala

Process was imported from SBT. Here's a thorough guide on how to use the process library as it appears in SBT.

https://github.com/harrah/xsbt/wiki/Process

Solution 4 - Scala

> Has anybody got an example on how to > actually start a process?

import sys.process._ // Package object with implicits!
"ls"!

> And, which is most interesting for me: > Can you detach processes?

"/path/to/script.sh".run()

Most of what you'll do is related to sys.process.ProcessBuilder, the trait. Get to know that.

There are implicits that make usage less verbose, and they are available through the package object sys.process. Import its contents, like shown in the examples. Also, take a look at its scaladoc as well.

Solution 5 - Scala

The following function will allow easy use if here documents:

def #<<< (command: String) (hereDoc: String) =
{
    val process = Process (command)
    val io = new ProcessIO (
        in  => {in.write (hereDoc getBytes "UTF-8"); in.close},
        out => {scala.io.Source.fromInputStream(out).getLines.foreach(println)},
        err => {scala.io.Source.fromInputStream(err).getLines.foreach(println)})
    process run io
}

Sadly I was not able to (did not have the time to) to make it an infix operation. Suggested calling convention is therefore:

#<<< ("command") {"""
Here Document data
"""}

It would be call if anybody could give me a hint on how to make it a more shell like call:

"command" #<<< """
Here Document data
""" !

Solution 6 - Scala

Documenting process a little better was second on my list for probably two months. You can infer my list from the fact that I never got to it. Unlike most things I don't do, this is something I said I'd do, so I greatly regret that it remains as undocumented as it was when it arrived. Sword, ready yourself! I fall upon thee!

Solution 7 - Scala

If I understand the dialog so far, one aspect of the original question is not yet answered:

  1. how to "detach" a spawned process so it continues to run independently of the parent scala script

The primary difficulty is that all of the classes involved in spawning a process must run on the JVM, and they are unavoidably terminated when the JVM exits. However, a workaround is to indirectly achieve the goal by leveraging the shell to do the "detach" on your behalf. The following scala script, which launches the gvim editor, appears to work as desired:

val cmd = List(
"scala",
"-e",
"""import scala.sys.process._ ; "gvim".run ; System.exit(0);"""
)
val proc = cmd.run

It assumes that scala is in the PATH, and it does (unavoidably) leave a JVM parent process running as well.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartinView Question on Stackoverflow
Solution 1 - Scalamichael.kebeView Answer on Stackoverflow
Solution 2 - ScalaAlex CruiseView Answer on Stackoverflow
Solution 3 - ScalaSynessoView Answer on Stackoverflow
Solution 4 - ScalaDaniel C. SobralView Answer on Stackoverflow
Solution 5 - ScalaMartinView Answer on Stackoverflow
Solution 6 - ScalapspView Answer on Stackoverflow
Solution 7 - ScalaPhilWView Answer on Stackoverflow