2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

scalaでinteractiveなshellコマンドを実行する

Last updated at Posted at 2018-12-30

lispでやってるのを見てscalaだとどんな感じになるのかな?と思って調べた
この辺を参照
https://stackoverflow.com/questions/30103040/interact-i-o-with-an-external-process-in-scala
https://github.com/scala/scala/blob/99a82be91cbb85239f70508f6695c6b21fd3558c/src/scaladoc/scala/tools/nsc/doc/html/page/diagram/DotRunner.scala

import java.io._
import scala.sys.process._


object Main extends App {
  val procIO = new ProcessIO(inputFn(_), outputFn(_), outputFn(_))
  val processBuilder = Process("/bin/bash")
  val process = processBuilder.run(procIO)

  private[this] def inputFn(stdin: OutputStream): Unit = {
    val writer = new BufferedWriter(new OutputStreamWriter(stdin))
    while (true) {
      val in = io.StdIn.readLine()
      writer.write(in + "\n")
      writer.flush()
      if (in == "exit") {
        return
      }
    }
    stdin.close()
  }
  private[this] def outputFn(stdOut: InputStream): Unit = {
    val reader = new BufferedReader(new InputStreamReader(stdOut))
    var line = reader.readLine
    while (line != null) {
      println(line)
      line = reader.readLine
    }
    stdOut.close()
  }
}

lispと違ってscalaだとあまり使う機会ないけどね〜


おまけ

val processBuilder = Process(Seq("/usr/local/bin/docker", "exec", "-i", <your docker container name>, "bash"))

こうすることでdocker execを実行することもできる

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?