python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python Java交互

Python与Java进行相互操作与调用的解决方案大全

作者:猫头虎

Python与Java是两种流行的编程语言,各自有不同的优势,在某些应用场景下,我们需要让Python和Java相互调用,下面小编就为大家介绍一下几种Python与Java互操作的方法吧

引言

Python与Java是两种流行的编程语言,各自有不同的优势。Java适用于大型企业级应用,而Python则因其简洁和强大的生态系统而广受欢迎。在某些应用场景下,我们需要让Python和Java相互调用,例如:

本文将介绍几种Python与Java互操作的方法,并通过代码示例详细展示每种方案的实现方式

方案1:使用Jython

Jython是一个运行在JVM上的Python解释器,允许Python代码直接调用Java代码。

安装Jython

wget https://www.jython.org/downloads/jython-installer-2.7.2.jar
java -jar jython-installer-2.7.2.jar

Python调用Java代码

from java.util import ArrayList

list_obj = ArrayList()
list_obj.add("Hello")
list_obj.add("World")

for item in list_obj:
    print(item)

Java调用Python代码

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!')");
    }
}

优点:

缺点:

方案2:使用JPype

JPype可以让Python直接调用Java的类方法,并且运行效率较高。

安装JPype

pip install jpype1

Python调用Java代码

import jpype
import jpype.imports

# 启动JVM
jpype.startJVM(classpath=["myjava.jar"])

from java.lang import System
System.out.println("Hello from Java!")

jpype.shutdownJVM()

优点:

缺点:

需要JVM环境。

方案3:使用Py4J

Py4J提供了一种轻量级的方式,使Python可以调用Java代码,适用于大多数场景。

安装Py4J

pip install py4j

Java服务器端代码

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();
    }
}

Python客户端代码

from py4j.java_gateway import JavaGateway

gateway = JavaGateway()
java_app = gateway.entry_point
print(java_app.hello("Python"))

优点:

缺点:

方案4:使用Jep(Java Embedded Python)

Jep可以让Java嵌入Python代码,适用于Java调用Python的场景。

安装Jep

pip install jep

Java调用Python代码

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和Java的环境兼容。

方案5:使用gRPC进行跨语言通信

gRPC是一个高效的RPC框架,支持Python和Java的交互。

定义gRPC服务(.proto文件)

syntax = "proto3";
service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply);
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

Python服务器端实现

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()

Java客户端实现

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服务配置。

总结

方案适用场景主要优点主要缺点
JythonJVM环境,Python 2直接运行在JVM,无需额外通信仅支持Python 2
JPypePython调用Java运行高效需要JVM
Py4J轻量级通信易用需要Java服务器
JepJava调用Python高效需要兼容环境
gRPC分布式系统高效远程调用需要额外配置

选择合适的方案取决于项目需求

到此这篇关于Python与Java进行相互操作与调用的解决方案大全的文章就介绍到这了,更多相关Python Java交互内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文