1.使用jython来实现java程序来调用python程序
在这种方法中可以实现直接调用python文件中的某一个函数并且传递参数,但是目前只支持python2.x版本,python3.x版本的代码没有办法执行,除此之外,还不支持很多python的第三方库,在使用第三方库的代码也不能正常执行
使用方法
首先需要导入相应的依赖
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.2</version>
</dependency>
之后就是编写相应的类来调用python代码
package com.ycc.patentsearch.util;
import org.python.util.PythonInterpreter;
import org.python.core.*;
public class JythonExample {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
// 执行Python脚本
interpreter.execfile("C:\\Users\\59717\\PycharmProjects\\pythondemo\\chap1\\addFun.py");
// 调用Python函数
PyObject yourFunction = interpreter.get("add");
//传递4个整形参数
PyObject[] params = new PyObject[]{new PyInteger(1), new PyInteger(2), new PyInteger(3), new PyInteger(4)};
PyObject result = yourFunction.__call__(params);
// 打印结果
System.out.println("Python function output: " + result);
System.out.println("-------------------------------------------------");
PyObject sort = interpreter.get("sort");
//传递4个整形参数
PyObject[] params1 = new PyObject[]{new PyInteger(12), new PyInteger(2), new PyInteger(3), new PyInteger(4), new PyInteger(7), new PyInteger(82), new PyInteger(41), new PyInteger(414)};
PyObject result1 = sort.__call__(new PyList(params1));
System.out.println("result1 = " + result1);
}
}
调用的python代码的示例如下
# -*- coding: utf-8 -*-
#写一个可以计算任意多个数字的函数
def add(*args):
total = 0
for val in args:
total += val
return total
#写一个排序函数,可以对列表、元组进行排序(冒泡排序)
def sort(seq):
for i in range(len(seq)):
for j in range(i+1,len(seq)):
if seq[i] > seq[j]:
seq[i],seq[j] = seq[j],seq[i]
return seq
#主函数实现任意个数字相加
if __name__ == '__main__':
print(add(1,2,3,4,5))
2.使用Runtime.getRuntime()执行python脚本文件(实质就是执行一条cmd命令)
这种方法只能调用执行python脚本中的主函数,不能执行python中的特定功能函数,而且传递参数的局限性很大,只能够传递字符串类型的参数(参数的长度好像也是受限制的)
使用方法
package com.ycc.patentsearch.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class testParams {
public static void main(String[] args) throws IOException {
try {
String[] args1 = new String[] {"python", "C:\\Users\\59717\\PycharmProjects\\pythondemo\\chap1\\testParams.py", "电脑","擦拭"};
Process proc = Runtime.getRuntime().exec(args1);
// 读取Python函数的输出
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(),"gb2312"));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
// 读取Python函数的错误输出
BufferedReader err = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
while ((line = err.readLine()) != null) {
System.err.println(line);
}
in.close();
err.close();
proc.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
调用的python代码示例
# -*- coding: utf-8 -*-
#定义一个接收字符串类型的参数的函数
import sys
def get_similar_words():
return sys.argv[1] + " is a keyword1 " + sys.argv[2] + " is a keyword2"
if __name__ == "__main__":
print(get_similar_words())
3.使用ProcessBuilder调用python脚本
ProcessBuilder和Runtime.getRuntime().exec()都可以用来在Java中执行外部命令,但它们之间存在一些差异:
- 参数传递:Runtime.exec()方法接受一个字符串作为命令,这个字符串会被空格分割成多个参数。如果命令或参数中包含空格,那么这种分割可能会导致问题。而ProcessBuilder接受一个字符串列表,每个字符串都是一个独立的参数,因此可以更准确地处理包含空格的命令和参数。
- 错误处理:ProcessBuilder有一个redirectErrorStream()方法,可以将错误输出和标准输出合并到一个流中,这样可以更方便地处理输出。而Runtime.exec()则需要分别处理标准输出和错误输出。
- 环境变量:ProcessBuilder提供了一个environment()方法,可以获取和修改进程的环境变量。而Runtime.exec()则没有提供类似的功能。
- 工作目录:ProcessBuilder提供了一个directory()方法,可以设置进程的工作目录。而Runtime.exec()则总是在Java进程的当前工作目录中执行命令。
因此,虽然ProcessBuilder和Runtime.getRuntime().exec()都可以用来执行外部命令,但ProcessBuilder提供了更多的灵活性和控制。在处理复杂的命令和参数,或者需要修改环境变量和工作目录时,ProcessBuilder可能是更好的选择。
public static void main(String[] args) throws Exception {
// Python脚本的路径
String pythonScriptPath = "C:\\Users\\59717\\PycharmProjects\\pythondemo\\chap1\\testParams.py";
// Python函数的名称,并不能根据这个来选择函数执行,只能作为一个参数,在python的主函数中进行判断
String pythonFunctionName = "get_similar_words";
// Python函数的参数
String pythonFunctionArgs = "music";
// 使用ProcessBuilder来执行Python脚本
ProcessBuilder pb = new ProcessBuilder(Arrays.asList("python", pythonScriptPath, pythonFunctionName, pythonFunctionArgs));
Process p = pb.start();
// 读取Python函数的输出
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println("Python function output: " + line);
}
// 读取Python函数的错误输出
BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = err.readLine()) != null) {
System.err.println("Python function error: " + line);
}
}