Scala 进程 - 捕获标准输出和退出代码 [英] Scala Process - Capture Standard Out and Exit Code

查看:37
本文介绍了Scala 进程 - 捕获标准输出和退出代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Scala scala.sys.process 库.

I'm working with the Scala scala.sys.process library.

我知道我可以用 ! 捕获退出代码,用 !! 捕获输出,但是如果我想同时捕获两者呢?

I know that I can capture the exit code with ! and the output with !! but what if I want to capture both?

我看过这个答案https://stackoverflow.com/a/6013932/416338,看起来很有希望,但我想知道是否有一个班轮,我错过了什么.

I've seen this answer https://stackoverflow.com/a/6013932/416338 which looks promising, but I'm wondering if there is a one liner and I'm missing something.

推荐答案

您可以使用 ProcessIO.我在 Specs2 测试中需要类似的东西,在那里我必须检查退出值以及进程的输出,具体取决于 stdin(inincode>out 属于 String) 类型:

You can use ProcessIO. I needed something like that in a Specs2 Test, where I had to check the exit value as well as the output of a process depending on the input on stdin (in and out are of type String):

"the operation" should {
  f"return '$out' on input '$in'" in {
    var res = ""
    val io = new ProcessIO(
      stdin  => { stdin.write(in.getBytes)
                  stdin.close() }, 
      stdout => { res = convertStreamToString(stdout)
                  stdout.close() },
      stderr => { stderr.close() })
    val proc = f"$operation $file".run(io)
    proc.exitValue() must be_==(0)
    res must be_==(out)
  }
}

我想这可能对你有帮助.在示例中,我忽略了来自 stderr 的内容.

I figured that might help you. In the example I am ignoring what ever comes from stderr.

这篇关于Scala 进程 - 捕获标准输出和退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆