发布时间:2019-09-06 08:53:45编辑:auto阅读(2235)
scala项目中调用python的几种方法
首先在工程目录某个地方建立了一个python文件
test.py
import sys
def addNum(a, b):
return a + b
if __name__ == '__main__':
a = 3
b = 7
# if args input
if len(sys.argv) == 3:
a = int(sys.argv[1])
b = int(sys.argv[2])
x = addNum(a, b)
print x
with open("src/test.txt", 'w') as f:
f.write("the result: " + str(x))
在scala里面启动一个本地进程,执行python程序
// method1: launch local runtime process to exec python file
// just exec file
val proc1 = Runtime.getRuntime().exec("python src/test.py")
proc1.waitFor()
// exec with parameters
val proc2 = Runtime.getRuntime().exec("python src/test.py 8 9")
proc2.waitFor()
其中:
Jpython(http://www.jython.org/)是一个java的扩展包,在scala里面可以直接调用
首先将Jpyhon standaone的jar文件导入到scala工程并引用
import org.python.core.{PyFunction, PyInteger, PyObject}
import org.python.util.PythonInterpreter
// method2: use Jpython module
val interpreter = new PythonInterpreter()
// exec python code
interpreter.exec("print 'hello jpython'")
// exec python file in JVM
val py_file = new FileInputStream("src/test.py")
interpreter.execfile(py_file)
py_file.close()
// call python funtion and return result (oops: work in java but not in scala ~)
// val a = 15
// val b = 17
// val func = interpreter.get("addNum", PyFunction.class).asInstanceOf[PyFunction]
// val pyobj = func.__call__(new PyInteger(a), new PyInteger(b))
// println(pyobj.toString())
其中:
上一篇: Python创建界面程序
下一篇: Python的定时器
47863
46424
37314
34760
29332
25990
24945
19967
19564
18050
5806°
6433°
5947°
5975°
7080°
5926°
5963°
6456°
6418°
7798°