【发布时间】:2020-05-18 20:02:13
【问题描述】:
尝试从 scala 调用 python 函数失败并出现以下错误。但是当直接从命令行调用相同的命令时工作正常。
请在下面找到简化代码 sn-ps :-
greeting.py
import logging
import os
def greet(arg):
print("hey " + arg)
StraightPyCall.scala
package git_log
object StraightPyCall {
def main(args: Array[String]): Unit = {
val commandWithNewLineInBeginning =
"""
|python -c "import sys;sys.path.append('~/playground/octagon/bucket/pythonCheck'); from greeting import *; greet('John')"
|""".stripMargin
//new line stripped out from beginning and end
val executableCommand = commandWithNewLineInBeginning.substring(1, commandWithNewLineInBeginning.length - 1)
println("command is :-")
println(executableCommand)
import sys.process._
s"$executableCommand".!!
}
}
上述scala程序的输出是:-
command is :-
python -c "import sys;sys.path.append('~/playground/octagon/bucket/pythonCheck'); from greeting import *; greet('John')"
File "<string>", line 1
"import
^
SyntaxError: EOL while scanning string literal
Exception in thread "main" java.lang.RuntimeException: Nonzero exit value: 1
at scala.sys.package$.error(package.scala:26)
at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.slurp(ProcessBuilderImpl.scala:134)
at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$bang$bang(ProcessBuilderImpl.scala:104)
at git_log.StraightPyCall$.main(StraightPyCall.scala:19)
at git_log.StraightPyCall.main(StraightPyCall.scala)
当我尝试执行打印在控制台上的命令时。它工作得很好。
python -c "import sys;sys.path.append('~/playground/octagon/bucket/pythonCheck'); from greeting import *; greet('John')"
结果:-
嘿约翰
注意:下面是 ProcessBuilder toString 表示(在调试时从堆栈跟踪复制):-
[python, -c, "import, sys;sys.path.append('/Users/mogli/jgit/code-conf/otherScripts/pythonScripts/CallRelativePyFromBash/pyscripts');, from, Greet, import, *;, greet_with_arg('John')"]
请建议,在 commandWithNewLineInBeginning 中需要修改什么以使其在 scala 中工作
【问题讨论】:
标签: python scala function processbuilder