Scala Process - Capture Standard Out and Exit Code

后端 未结 6 2249
心在旅途
心在旅途 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 07:00

    The one-line-ish use of BasicIO or ProcessLogger is appealing.

    scala> val sb = new StringBuffer
    sb: StringBuffer = 
    
    scala> ("/bin/ls /tmp" run BasicIO(false, sb, None)).exitValue
    res0: Int = 0
    
    scala> sb
    res1: StringBuffer = ...
    

    or

    scala> import collection.mutable.ListBuffer
    import collection.mutable.ListBuffer
    
    scala> val b = ListBuffer[String]()
    b: scala.collection.mutable.ListBuffer[String] = ListBuffer()
    
    scala> ("/bin/ls /tmp" run ProcessLogger(b append _)).exitValue
    res4: Int = 0
    
    scala> b mkString "\n"
    res5: String = ...
    

    Depending on what you mean by capture, perhaps you're interested in output unless the exit code is nonzero. In that case, handle the exception.

    scala> val re = "Nonzero exit value: (\\d+)".r.unanchored
    re: scala.util.matching.UnanchoredRegex = Nonzero exit value: (\d+)
    
    scala> Try ("./bomb.sh" !!) match {
         | case Failure(f) => f.getMessage match {
         |   case re(x) => println(s"Bad exit $x")
         | }
         | case Success(s) => println(s)
         | }
    warning: there were 1 feature warning(s); re-run with -feature for details
    Bad exit 3
    

提交回复
热议问题