Oct-13-2016, 09:01 AM
I'm a java developer and need call Python from JAVA sometimes. I google that but didn't find a satisfy way to do it. The Jython is clear and simple, but it is not CPython and doesn't support external C package, also slower than CPython. Process and Runtime method is not easily to get a well format result. Other bridge solutions solve such problems, but inject additional codes. So finally I decided to invent the wheel myself, took me 5 nights, now it works fine in my project, so I hope it has a little help for you too. It is open source and can find it on GitHub: jpserve (https://github.com/johnhuang-cn/jpserve)
JPserve provides a simple way to call Python and exchange the result by well format JSON, few performance loss.
The following is a simple sample.
At first, install jpserve by "pip -install jpserve" and start jpserve on Python side, jpserve is a script executor server executes the script from JAVA side.
JPserve provides a simple way to call Python and exchange the result by well format JSON, few performance loss.
The following is a simple sample.
At first, install jpserve by "pip -install jpserve" and start jpserve on Python side, jpserve is a script executor server executes the script from JAVA side.
from jpserve.jpserve import JPServe
serve = JPServe(("localhost", 8888))
serve.start()Output:INFO:JPServe:JPServe starting...
INFO:JPServe:JPServe listening in localhost 8888Then call Python from JAVA side:PyServeContext.init("localhost", 8888);
PyExecutor executor = PyServeContext.getExecutor();
script = "a = 2\n"
+ "b = 3\n"
+ "_result_ = a * b";
PyResult rs = executor.exec(script);
System.out.println("Result: " + rs.getResult());Output:Result: 6
