我也是试了好几个, 要么交互麻烦, 比如用Process方式, 要么不支持扩展包, 比如jython, 要么调用麻烦, 要么性能不够好, 所以最后自己造轮子写了jpserve. 调用简单, 性能和直接在Python跑没有差别, 交互方便通过JSON自动序列和反序列化法.
Python端需要3行代码启动jpserve:
>>> from jpserve.jpserve import JPServe
>>> serve = JPServe(("localhost", 8888))
>>> serve.start()
INFO:JPServe:JPServe starting...
INFO:JPServe:JPServe listening in localhost 8888
Java端调用也很直观,基本就是直接把脚本扔进去取结果就好了:
// init the PyServeContext, it will make a connection to JPServe
PyServeContext.init("localhost", 8888);
// prepare the script, and assign the return value to _result_
String script = "a = 2\n"
+ "b = 3\n"
+ "_result_ = a * b";
// sned the script to PyServe, it returns the final result
PyResult rs = executor.exec(script);
// check if the execution is success
if (rs.isSuccess()) {
System.out.println("Result: " + rs.getResult()); // get the _result_ value
}
else {
System.out.println("Execute python script failed: " + rs.getMsg());
}
------------------------
Result: 6