如何使用带有来自scala的python -c命令的args运行python代码

我有
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)

最佳答案 您可以利用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))
  }
}
点赞