文章目录
- wget https://www.jython.org/downloads/jython-installer-2.7.2.jar java -jar jython-installer-2.7.2.jar
- from java.util import ArrayList list_obj = ArrayList() list_obj.add(“Hello”) list_obj.add(“World”) for item in list_obj: print(item)
- Jython提供了PythonInterpreter类,可以在Java代码中执行Python脚本。 import org.python.util.PythonInterpreter; public class JythonExample { public static void main(String[] args) { PythonInterpreter interpreter = new PythonInterpreter(); interpreter.exec(“print(‘Hello from Python!’)”); } } 优点: 直接运行在JVM上,无需额外的进程通信。 能够直接使用Java类。 缺点: Jython仅支持Python 2,不支持Python 3。
- pip install py4j
- import py4j.GatewayServer; public class JavaApp { public String hello(String name) { return “Hello, ” + name; } public static void main(String[] args) { JavaApp app = new JavaApp(); GatewayServer server = new GatewayServer(app); server.start(); } }
- from py4j.java_gateway import JavaGateway gateway = JavaGateway() java_app = gateway.entry_point print(java_app.hello(“Python”)) 优点: 轻量级,不依赖JVM。 适用于分布式系统。 缺点: 需要启动Java服务器。
- syntax = “proto3”; service Greeter { rpc SayHello (HelloRequest) returns (HelloReply); } message HelloRequest { string name = 1; } message HelloReply { string message = 1; }
- import grpc from concurrent import futures import hello_pb2 import hello_pb2_grpc class GreeterServicer(hello_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return hello_pb2.HelloReply(message=f”Hello, {request.name}!”) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) hello_pb2_grpc.add_GreeterServicer_to_server(GreeterServicer(), server) server.add_insecure_port(‘[::]:50051’) server.start() server.wait_for_termination()
- import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import hello.GreeterGrpc; import hello.HelloRequest; public class GrpcClient { public static void main(String[] args) { ManagedChannel channel = ManagedChannelBuilder.forAddress(“localhost”, 50051).usePlaintext().build(); GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel); HelloRequest request = HelloRequest.newBuilder().setName(“Java”).build(); System.out.println(stub.sayHello(request).getMessage()); channel.shutdown(); } } 优点: 高效,支持远程调用。 适用于微服务架构。 缺点: 需要额外的gRPC服务配置。
目录
- 引言
- 方案1:使用Jython
- 安装Jython
- Python调用Java代码
- Java调用Python代码
- 方案2:使用JPype
- 安装JPype
- Python调用Java代码
- 方案3:使用Py4J
- 安装Py4J
- Java服务器端代码
- Python客户端代码
- 方案4:使用Jep(Java Embedded Python)
- 安装Jep
- Java调用Python代码
- 方案5:使用gRPC进行跨语言通信
- 定义gRPC服务(.proto文件)
- Python服务器端实现
- Java客户端实现
- 总结
Python与Java是两种流行的编程语言,各自有不同的优势。Java适用于大型企业级应用,而Python则因其简洁和强大的生态系统而广受欢迎。在某些应用场景下,我们需要让Python和Java相互调用,例如:
- 在Java应用中使用Python进行数据分析或机器学习。
- 在Python中调用Java编写的高性能计算模块。
- 结合Python和Java的丰富库,提高开发效率。
本文将介绍几种Python与Java互操作的方法,并通过代码示例详细展示每种方案的实现方式
Jython是一个运行在JVM上的Python解释器,允许Python代码直接调用Java代码。
wget https://www.jython.org/downloads/jython-installer-2.7.2.jar
java -jar jython-installer-2.7.2.jar
from java.util import ArrayList
list_obj = ArrayList()
list_obj.add("Hello")
list_obj.add("World")
for item in list_obj:
print(item)
Jython提供了PythonInterpreter类,可以在Java代码中执行Python脚本。
import org.python.util.PythonInterpreter;
public class JythonExample {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("print('Hello from Python!')");
}
}
优点:
- 直接运行在JVM上,无需额外的进程通信。
- 能够直接使用Java类。
缺点:
- Jython仅支持Python 2,不支持Python 3。
JPype可以让Python直接调用Java的类方法,并且运行效率较高。
pip install jpype1
import jpype
import jpype.imports
# 启动JVM
jpype.startJVM(classpath=["myjava.jar"])
from java.lang import System
System.out.println("Hello from Java!")
jpype.shutdownJVM()
优点:
- 运行效率高,直接调用Java方法。
- 支持Python 3。
缺点:
需要JVM环境。
Py4J提供了一种轻量级的方式,使Python可以调用Java代码,适用于大多数场景。
pip install py4j
import py4j.GatewayServer;
public class JavaApp {
public String hello(String name) {
return "Hello, " + name;
}
public static void main(String[] args) {
JavaApp app = new JavaApp();
GatewayServer server = new GatewayServer(app);
server.start();
}
}
from py4j.java_gateway import JavaGateway
gateway = JavaGateway()
java_app = gateway.entry_point
print(java_app.hello("Python"))
优点:
- 轻量级,不依赖JVM。
- 适用于分布式系统。
缺点:
- 需要启动Java服务器。
Jep可以让Java嵌入Python代码,适用于Java调用Python的场景。
pip install jep
import jep.Interpreter;
import jep.SharedInterpreter;
public class JepExample {
public static void main(String[] args) {
try (Interpreter interp = new SharedInterpreter()) {
interp.exec("print('Hello from Python!')");
}
}
}
优点:
- 运行速度快。
- 支持Python 3。
缺点:
需要Python和Java的环境兼容。
gRPC是一个高效的RPC框架,支持Python和Java的交互。
syntax = "proto3";
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
import grpc
from concurrent import futures
import hello_pb2
import hello_pb2_grpc
class GreeterServicer(hello_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return hello_pb2.HelloReply(message=f"Hello, {request.name}!")
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
hello_pb2_grpc.add_GreeterServicer_to_server(GreeterServicer(), server)
server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import hello.GreeterGrpc;
import hello.HelloRequest;
public class GrpcClient {
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051).usePlaintext().build();
GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
HelloRequest request = HelloRequest.newBuilder().setName("Java").build();
System.out.println(stub.sayHello(request).getMessage());
channel.shutdown();
}
}
优点:
- 高效,支持远程调用。
- 适用于微服务架构。
缺点:
需要额外的gRPC服务配置。
| 方案 | 适用场景 | 主要优点 | 主要缺点 |
|---|---|---|---|
| Jython | JVM环境,Python 2 | 直接运行在JVM,无需额外通信 | 仅支持Python 2 |
| JPype | Python调用Java | 运行高效 | 需要JVM |
| Py4J | 轻量级通信 | 易用 | 需要Java服务器 |
| Jep | Java调用Python | 高效 | 需要兼容环境 |
| gRPC | 分布式系统 | 高效远程调用 | 需要额外配置 |
选择合适的方案取决于项目需求
到此这篇关于Python与Java进行相互操作与调用的解决方案大全的文章就介绍到这了,更多相关Python Java交互内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!
您可能感兴趣的文章:
- python如何调用java的jar包
- Python与Java交互出现乱码的问题解决
- Java调用Python的四种方法小结
- Python与Java进行交互操作的方法与性能对比
- Java调用Python代码的几种方法小结
- 详细介绍使用Java调用Python的四种方法