在scala中抓取进程stderr

时间:2011-04-06 08:25:31

标签: scala process stderr

使用scala 2.9 process API时,我可以执行

之类的操作
"ls -l"!

将把进程stdout和stderr发送到我自己的进程中。 或者:

val output = "ls -1"!!

将把发送到stdout的内容返回到val输出。

我怎样才能同样抓住stderr?

1 个答案:

答案 0 :(得分:38)

您可以创建自己的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

编辑:上一个示例只是打印,但它可以轻松地将输出存储在某个结构中:

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.