Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grabbing process stderr in scala

When using the scala 2.9 process API, I can do things like

"ls -l"!

which will send the process stdout and stderr into my own. Or:

val output = "ls -1"!!

which will return whatever was sent to stdout into the val output.

How can I similarly grab stderr?

like image 320
Omry Yadan Avatar asked Apr 06 '11 08:04

Omry Yadan


1 Answers

You can create your own ProcessLogger:

import sys.process._

val logger = ProcessLogger(
    (o: String) => println("out " + o),
    (e: String) => println("err " + e))

scala> "ls" ! logger
out bin
out doc
out lib
out meta
out misc
out src
res15: Int = 0

scala> "ls -e" ! logger
err ls: invalid option -- e
err Try `ls --help' for more information.
res16: Int = 2

Edit: The previous example simply prints, but it could easily store the output in some structure:

val out = new StringBuilder
val err = new StringBuilder

val logger = ProcessLogger(
    (o: String) => out.append(o),
    (e: String) => err.append(e))

scala> "ls" ! logger
res22: Int = 0

scala> out
res23: StringBuilder = bindoclibmetamiscsrc

scala> "ls -e" ! logger
res27: Int = 2

scala> out
res28: StringBuilder =

scala> err
res29: StringBuilder = ls: invalid option -- eTry `ls --help' for more information.
like image 193
eivindw Avatar answered Nov 09 '22 14:11

eivindw