当使用scala 2.9进程API时,我可以做像
这样的事情"ls -l"!
,这将发送进程stdout和stderr到我自己的。或:
val output = "ls -1"!!
,它将返回发送到stdout的任何内容到val输出。
如何类似地抓取stderr?
你可以创建你自己的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.