从Java调用Python
jpserve的Python项目详细描述
JPSERVE
jpserve提供了一种在java中执行python脚本的简单高效的方法。它包括pyserve和jclient api。
- pyserve是一个运行在python端的执行服务器,它监听来自java的执行请求。
- jclient api可以从java中执行python片段或完整的脚本文件,将脚本发送到pyserve并得到执行结果。结果是JSON格式,因此您可以灵活地在Java和Python之间交换复杂数据。
快速启动
python端
打开python控制台,导入jpserve并启动pyserve:
>>> from jpserve.jpserve import PyServe >>> server = PyServe(("localhost", 8888)) >>> server.start() >>> INFO:pserve:starting... INFO:pserve:pyserve listening in localhost 8888 >>>
Java端
>>> // init the PyServeContext, it will make a connection to PyServe 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