在scala中抓取进程stderr [英] Grabbing process stderr in scala
本文介绍了在scala中抓取进程stderr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当使用 scala 2.9 进程 API 时,我可以做类似的事情
When using the scala 2.9 process API, I can do things like
"ls -l"!
它将进程 stdout 和 stderr 发送到我自己的.或者:
which will send the process stdout and stderr into my own. Or:
val output = "ls -1"!!
这会将发送到 stdout 的任何内容返回到 val 输出中.
which will return whatever was sent to stdout into the val output.
我怎样才能同样地抓取 stderr?
How can I similarly grab stderr?
推荐答案
您可以创建自己的 ProcessLogger:
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
前面的示例只是打印,但它可以轻松地将输出存储在某种结构中:
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.
这篇关于在scala中抓取进程stderr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文