Python与Java是两种流行的编程语言,各自有不同的优势。Java适用于大型企业级应用,而Python则因其简洁和强大的生态系统而广受欢迎。在某些应用场景下,我们需要让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!')");
}
}
优点:
缺点:
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()
优点:
缺点:
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"))
优点:
缺点:
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!')");
}
}
}
优点:
缺点:
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();
}
}
优点:
缺点:
方案 | 适用场景 | 主要优点 | 主要缺点 |
---|---|---|---|
Jython | JVM环境,Python 2 | 直接运行在JVM,无需额外通信 | 仅支持Python 2 |
JPype | Python调用Java | 运行高效 | 需要JVM |
Py4J | 轻量级通信 | 易用 | 需要Java服务器 |
Jep | Java调用Python | 高效 | 需要兼容环境 |
gRPC | 分布式系统 | 高效远程调用 | 需要额外配置 |
选择合适的方案取决于项目需求,希望本文对你有所帮助!