温馨提示×

Ubuntu下Python与Java如何互操作

小樊
49
2025-08-03 12:35:10
栏目: 编程语言

在Ubuntu系统下,Python与Java可以通过多种方式实现互操作。以下是一些常见的方法:

使用JPype库在Python中调用Java

JPype是一个允许Python代码直接调用Java类的库。以下是基本步骤:

  1. 安装JPype
pip3 install jpype1
  1. 打包Java代码为JAR
javac testDemo.java
jar cvf testDemo.jar testDemo.class
  1. 在Python中调用Java
from jpype import *
import os

# 启动Java虚拟机
startJVM("/usr/lib/jvm/java-11-openjdk-amd64/bin/java", "-ea", "-Djava.class.path=/path/to/testDemo.jar")

# 加载Java类
JClass("testDemo")

# 调用Java方法
result = JClass("testDemo").inputTest("Hello")
print(result)

# 关闭Java虚拟机
shutdownJVM()

使用Jython在Python中运行Java代码

Jython是Python语言的Java实现,允许Python代码直接调用Java类。以下是基本步骤:

  1. 安装Jython
wget https://downloads.apache.org//jython/2.7.2/jython-standalone-2.7.2.jar
java -jar jython-standalone-2.7.2.jar
  1. 编写Java代码(例如testDemo.java):
package com.example;

public class testDemo {
    public String inputTest(String input) {
        return "Input content: " + input;
    }
}
  1. 在Jython中调用Java
from com.example import testDemo

demo = testDemo()
print(demo.inputTest("Hello"))

使用Apache Thrift进行跨语言调用

Apache Thrift是一个跨语言的服务定义框架,支持多种语言包括Python和Java。以下是基本步骤:

  1. 定义Thrift文件(例如example.thrift):
namespace java com.example
namespace py com.example

service SharedService {
    string constMap(1: string mapConstant)
    struct Work {
        1: i32 num1
        2: i32 num2
        3: Operation op
        4: optional string comment
    }
    enum Operation {
        ADD = 1
        SUBTRACT = 2
        MULTIPLY = 3
        DIVIDE = 4
    }
    struct SharedStruct {
        1: i32 key
        2: string value
    }
    sharedStruct getSharedStruct(1: string key)
}
  1. 生成Java和Python代码
thrift --gen java example.thrift
thrift --gen py example.thrift
  1. 在Java中实现服务
package com.example;

import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.server.TThreadPoolServer.Args;
import org.apache.thrift.impl.TMultiplexedProtocol;
import org.apache.thrift.impl.TProtocolFactory;
import org.apache.thrift.impl.TTransportFactory;

public class SharedServiceImpl implements SharedService.Iface {
    @Override
    public Map<String, String> constMap(String mapConstant) {
        Map<String, String> result = new HashMap<>();
        result.put("mapConstant", mapConstant);
        return result;
    }

    public static void main(String[] args) {
        try {
            TTransport transport = new TSocket("localhost", 9090);
            transport.open();
            TProtocol protocol = new TBinaryProtocol(transport);
            SharedService.Client client = new SharedService.Client(protocol);
            TMultiplexedProtocol multiplexedProtocol = new TMultiplexedProtocol(protocol, "shared");
            SharedService.Client sharedClient = new SharedService.Client(multiplexedProtocol);
            Map<String, String> result = sharedClient.constMap("hello:world");
            System.out.println(result);
            transport.close();
        } catch (TTransportException e) {
            e.printStackTrace();
        }
    }
}
  1. 在Python中调用Java服务
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from shared_service import SharedService

transport = TSocket.TSocket('localhost', 9090)
transport.open()
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = SharedService.Client(protocol)

client.constMap({'key': 'value'})

使用ProcessBuilder类在Java中调用Python脚本

Java的ProcessBuilder类可以用于执行Python脚本并捕获其输出。以下是基本步骤:

  1. 编写Python脚本(例如hello.py):
import sys

args = sys.argv
print("Hello from Python!")
print("Received arguments:", args[1:])
  1. 在Java中调用Python脚本
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PythonCaller {
    public static void main(String[] args) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("python", "hello.py");
            Process process = processBuilder.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();

            int exitCode = process.waitFor();
            System.out.println("Process exited with code " + exitCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这些方法各有优劣,具体选择哪一种取决于项目的具体需求和环境。

0