项目中java调用python接口_java web该如何调用python项目执行,以及相互之间的交互传递数据?...

我也是试了好几个, 要么交互麻烦, 比如用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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值