您的位置:首页 > 编程语言 > Python开发

如何在Java项目中执行python代码

2018-01-23 16:41 246 查看
  最近在做一个项目,需要在java里调用python代码,网上找了一些资料,想简单总结一下。可是我对java运行机制并不是很了解,所以只能说说怎么做。

1. 安装Jython (什么是Jython)

下载安装jython_installer-2.5.0.jar, 安装完毕后需要把其中的jython.jar复制到项目中的lib中(引入jar包);

2. 编写简易python代码

import java.io.IOException;
import org.python.util.PythonInterpreter;
public class test {
public static void main(String args[]) throws IOException {
PythonInterpreter interpreter = new PythonInterpreter();
// 运行python语句
interpreter.exec("a = \"hello, Jython\"");
interpreter.exec("print a");

}
} 结果报错:console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.

把上述代码改成下面形式即可

import java.io.IOException;
import org.python.util.PythonInterpreter;
public class test {
public static void main(String args[]) throws IOException {
<span class="space" style="white-space:pre;display:inline-block;text-indent:2em;line-height:inherit"> </span><span class="space" style="white-space:pre;display:inline-block;text-indent:2em;line-height:inherit"> </span><span class="space" style="white-space:pre;display:inline-block;text-indent:2em;line-height:inherit"> </span><span class="space" style="white-space:pre;display:inline-block;text-indent:2em;line-height:inherit"> </span>Properties props = new Properties();
props.put("python.console.encoding", "UTF-8"); // Used to prevent: console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.
props.put("python.security.respectJavaAccessibility", "false"); //don't respect java accessibility, so that we can access protected members on subclasses
props.put("python.import.site","false");
Properties preprops = System.getProperties();
PythonInterpreter.initialize(preprops, props, args);
PythonInterpreter interpreter = new PythonInterpreter();
// 运行python语句
interpreter.exec("a = \"hello, Jython\"");
interpreter.exec("print a");

}
} 3. 执行python文件

把上述执行python语句的代码改为

interpreter.execfile("C:/Users/JingYi/Desktop/hello.py"); ///执行python py文件
4. 执行python文件并传参

package jp;
import java.util.Properties;
import org.python.core.Py;
import org.python.core.PyException;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;

public class main {

public static void main(String args[]) {

Properties props = new Properties();
props.put("python.console.encoding", "UTF-8"); // Used to prevent: console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.
props.put("python.security.respectJavaAccessibility", "false"); //don't respect java accessibility, so that we can access protected members on subclasses
props.put("python.import.site","false");
Properties preprops = System.getProperties();
String[] arguments ={ "string1", "string2","string3"};
PythonInterpreter.initialize(preprops, props, arguments);
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys");
interpreter.exec("sys.path.append('E:/Python27/Lib')"); // 加载第三方包的路径
interpreter.exec("sys.path.append('E:/Python27/Lib/site-packages')"); // 加载第三方包的路径
interpreter.exec("sys.path.append('E:/Python27/Lib/site-packages/numpy/lib')"); // 加载第三方包的路径

interpreter.execfile("C:/Users/JingYi/Desktop/hello.py"); //执行python文件
String funcName ="myFunction";
PyObject someFunc =interpreter.get(funcName); // 调用python的猴哥函数

if (someFunc == null) {
//throw new Exception("Could notfind Python function: " + funcName);
}
else
{
someFunc.__call__(new PyString(arguments[0]), new PyString(arguments[1]), new PyString(arguments[2])); // 把参数传过去
}

}// main

}
其中hello.py文件内容如下:

def myFunction(str1, str2, str3):
print 'print parameters from java'
print str1
print str2
print str3
5. 引入第三方库

根据上述方法,暂时不清楚如何在jython中引用类似numpy pandas这样的第三方库,这里给出一种实现方法(与jython无关)。
package jp;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class test {
public static void main(String[] args){
try{
System.out.println("start");
Process pr = Runtime.getRuntime().exec("E:\\Python27\\python.exe C:/Users/JingYi/Desktop/hello.py");  // 本机的python运行环境 & 即将要调用的py文件

BufferedReader in = new BufferedReader(new
InputStreamReader(pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
pr.waitFor();
System.out.println("end");
} catch (Exception e){
e.printStackTrace();
}
}
}

参考:

1.  Jython:java调用python文件之第三方包路径问题 java调用python总出现python第三方库没有定义


2.  java调用python总出现python第三方库没有定义
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: