在scala中抓取进程stderr

发布于 2024-10-31 00:26:01 字数 235 浏览 1 评论 0原文

当使用 scala 2.9 进程 API 时,我可以执行类似的操作,

"ls -l"!

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

val output = "ls -1"!!

它将把发送到 stdout 的所有内容返回到 val 输出中。

我怎样才能类似地获取stderr?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泅渡 2024-11-07 00:26:01

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

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文