如何从Scala使用python -c命令与args一起运行python代码

时间:2019-01-23 15:26:05

标签: scala

我有python代码,例如:

import sys

print('1')
print("2")
print(sys.argv[1])

注意,它可以包含单引号,双引号并接受参数。

在我的服务中,我通过网络接收代码,应该执行它。我不想将代码临时保存为脚本在磁盘上,因此我想用python -c命令执行它。

我如何在bash(https://stackoverflow.com/a/29565580/1996639)中执行它:

$ python3 -c $'import sys\nprint(\'1\')\nprint("2")\nprint(sys.argv[1])' 3
1
2
3

我的问题:如何从scala执行示例代码?

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


  val code =
    """
      |import sys
      |
      |print('1')
      |print("2")
      |print(sys.argv[1])
    """.stripMargin

  val arg = 3

  val cmd = ???

  val (exitCode, std, err) = runCommand(cmd)

1 个答案:

答案 0 :(得分:1)

您可以利用Scala的ProcessBuilder方法也接受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))
  }
}