Created
January 14, 2012 22:52
-
-
Save toddsundsted/1613243 to your computer and use it in GitHub Desktop.
PLEAC: Process Management and Communication (Scala)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Process Management and Communication | |
* see http://pleac.sourceforge.net/pleac_perl/processmanagementetc.html | |
* Scala 2.9.1 | |
*/ | |
import scala.sys.process._ | |
import scala.io.Source | |
import java.io.File | |
/* Gathering Output From a Program */ | |
val output = "program args" !! // collect output into one multiline string | |
val output = ("program args" !!).split("\n") // collect output into array, one line per element | |
var output = "" | |
Process("program args").lines.foreach { line => | |
output += line | |
} | |
val output = Process("program args").lines.foldLeft("") { (out, line) => out + line } | |
val output = Process("program args").lines.foldLeft("")(_+_) | |
var output = "" | |
val p = Process(List("program", "arg1", "arg2")) | |
val pio = new ProcessIO(stdin => (), | |
stdout => Source.fromInputStream(stdout).getLines.foreach { line => output += line }, | |
stderr => Source.fromInputStream(stderr).getLines.foreach(println)) | |
p.run(pio) | |
/* Running Another Program */ | |
val file = "test.txt" | |
val status = "vi " + file !< // not without terminal issues on exit | |
val file = new File("test.txt") | |
List("ls", "-l") ### "echo -n" ### "echo -n" #> file ! | |
val infile = new File("infile.txt") | |
val outfile = new File("outfile.txt") | |
"cat" #< infile #> outfile ! // no obvious way to include stderr in the mix | |
(List("program", "arg1", "arg2") !) == 0 || sys.exit(-1) // jvm exits with code -1 | |
(List("program", "arg1", "arg2") !) == 0 || sys.error("fail") // jvm raises runtime exception | |
import sun.misc.{Signal, SignalHandler} // there is no completely portable signal management in java/scala | |
val signo = ("program arg1 arg2" !) & 127 | |
if (signo != 0) { | |
sys.error("program killed by signal " + signo) | |
} | |
Signal.handle( | |
new Signal("INT"), | |
new SignalHandler { | |
override def handle(signal: Signal) = println("Tsk tsk, no process interruptus") | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment