LoginSignup
5
6

More than 5 years have passed since last update.

Scalaで外部コマンドを実行して標準出力とエラーを取得する

Posted at

Scalaで外部コマンドの実行はscala.sys.processがあるおかけで、Javaよりも圧倒的に簡単!

// 実行結果を取得
Process(Seq("cmd", "/c", "dir")) !

Javaだとめんどくさい標準出力の取得もこれだけ

Process(Seq("cmd", "/c", "dir")) !!

これでStringで返ってくるのでとても便利。Listでの取得もできる。
ただ、実行結果と標準出力の両方が取れなくて地味に不便。そういうときはProcessLoggerを使えば良いらしい。

で、下記がProcessLoggerを使ったサンプル。

  case class ExecResult(result: Int, out: List[String], err: List[String])

  def exec(cmd: Seq[String]) = {
    import scala.collection.mutable._
    import scala.sys.process._

    val out = ArrayBuffer[String]()
    val err = ArrayBuffer[String]()

    val logger = ProcessLogger(
      (o: String) => out += o,
      (e: String) => err += e)

    val r = Process(cmd) ! logger

    ExecResult(r, out.toList, err.toList)
  }

実行はこんな感じ。

exec(Seq("cmd", "/c", "dir"))

これで、戻り値として実行結果と標準出力/エラーが返ってくるので色々はかどります。

それではHappy Hacking!

参考:

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6