从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如果我们在hibernate中开始事务但不提交它,会发生什么?   Azure CosmosDB Java Springboot中的无服务器帐户不支持spring boot设置提供吞吐量或容器自动导航   附加到新对象的Java注释?   java如何将自定义文本视图添加到。在Kotlin中添加通知操作   java Shibboleth添加_OpenSAMLcookies,导致HTTP头大小>8k   分布式传感器数据(~40Hz)的高效Java观测器设计   java如何在while循环外声明数组,但在while循环中初始化它?   用@XmlElementRef注释的java元素没有显示在JAXB编组字符串中?   java替换二维数组的值   java如何在任务栏上创建Windows7加载栏   java如何在组件注释bean中使用会话或RequestScope bean?   java netbeans freermarker插件错误:在实现版本中请求netbeans桥的插件Lexer   java谷歌地图方向。加载失败,返回服务器错误   java当我试图递归地计算两个值之间的整数之和时,为什么结果返回一个奇怪的值?   java如何通过html文件的用户获取运行时输入,以使用Jsoup进行解析?