score:1

Accepted answer

You can take advantage of the fact that Scala's ProcessBuilder methods also accept Seq[String].

import sys.process._
object SO {
  def runCommand(cmd: String*): (Int, String, String) = {
    val stdoutStream = new java.io.ByteArrayOutputStream
    val stderrStream = new java.io.ByteArrayOutputStream
    val stdoutWriter = new java.io.PrintWriter(stdoutStream)
    val stderrWriter = new java.io.PrintWriter(stderrStream)
    val exitValue =
      cmd.!(ProcessLogger(stdoutWriter.println, stderrWriter.println))
    stdoutWriter.close()
    stderrWriter.close()
    (exitValue, stdoutStream.toString, stderrStream.toString)
  }

  def main(args: Array[String]): Unit = {
    val code =
      """
        |import sys
        |
        |print('1')
        |print("2")
        |print(sys.argv[1])
      """.stripMargin

    val arg = 3
    println(runCommand("python3","-c", code, arg.toString))
  }
}

Related Query

More Query from same tag