Scala Process - Capture Standard Out and Exit Code

后端 未结 6 2254
心在旅途
心在旅途 2020-12-13 06:21

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

I know that I can capture the exit code with ! and the output with !!

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 06:54

    Here's a really simple Scala wrapper that allows you to retrieve stdout, stderr and exit code.

    import scala.sys.process._
    
    case class ProcessInfo(stdout: String, stderr: String, exitCode: Int)
    
    object CommandRunner {
    
    def runCommandAndGetOutput(command: String): ProcessInfo = {
        val stdout = new StringBuilder
        val stderr = new StringBuilder
        val status = command ! ProcessLogger(stdout append _, stderr append _)
        ProcessInfo(stdout.toString(), stderr.toString(), status)
      }
    }
    

提交回复
热议问题