从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

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
将Java小程序转换为应用程序   音频数据格式和文件格式Java声音   java如何使用jsoup维护变量cookie和会话?   您能否使用类似于Java中python关键字args的概念来最小化访问器方法的数量?   JavaSpring引导HTTPS和重定向   如何反转直角三角形(Java)   JavaPowerMockito:拦截所有静态方法   java Vaadin TouchKit基本主题问题   java如何指定文件的路径。要在其文件系统中动态加载的类文件?   java Google Play Services Unity   java MyBatis SQL Builder类,如%   java无法访问Internet Explorer中的小程序   java如何计算2d数组中的行之间的差异?   在GridBagLayout中调用SetContraints时发生java NullPointerException   java同步锁和独立线程:Android   泛型我能让这个java pulk()方法更安全吗?   java为火车线上的所有车站创建距离地图   java在素数阶循环群中查找元素   java正在查找什么类型的类