在Ubuntu系统下,Python与Java可以通过多种方式实现互操作。以下是一些常见的方法:
JPype是一个允许Python代码直接调用Java类的库。以下是基本步骤:
pip3 install jpype1
javac testDemo.java
jar cvf testDemo.jar testDemo.class
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实现,允许Python代码直接调用Java类。以下是基本步骤:
wget https://downloads.apache.org//jython/2.7.2/jython-standalone-2.7.2.jar
java -jar jython-standalone-2.7.2.jar
testDemo.java):package com.example;
public class testDemo {
public String inputTest(String input) {
return "Input content: " + input;
}
}
from com.example import testDemo
demo = testDemo()
print(demo.inputTest("Hello"))
Apache Thrift是一个跨语言的服务定义框架,支持多种语言包括Python和Java。以下是基本步骤:
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)
}
thrift --gen java example.thrift
thrift --gen py example.thrift
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();
}
}
}
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'})
Java的ProcessBuilder类可以用于执行Python脚本并捕获其输出。以下是基本步骤:
hello.py):import sys
args = sys.argv
print("Hello from Python!")
print("Received arguments:", args[1:])
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();
}
}
}
这些方法各有优劣,具体选择哪一种取决于项目的具体需求和环境。