如何在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文件并传参
def myFunction(str1, str2, str3):
print 'print parameters from java'
print str1
print str2
print str3
5. 引入第三方库
根据上述方法,暂时不清楚如何在jython中引用类似numpy pandas这样的第三方库,这里给出一种实现方法(与jython无关)。
参考:
1. Jython:java调用python文件之第三方包路径问题 java调用python总出现python第三方库没有定义
2. java调用python总出现python第三方库没有定义
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第三方库没有定义
相关文章推荐
- 手把手教你如何把java代码,打包成jar文件以及转换为exe可执行文件
- C# Javascript引擎,如何在C#中执行现有的Javacript代码?
- 手把手教你如何把java代码,打包成jar文件以及转换为exe可执行文件
- 手把手教你如何把java代码,打包成jar文件以及转换为exe可执行文件
- 手把手教你,如何把java代码打包成jar文件以及转换为exe可执行文件
- 手把手教你如何把java代码,打包成jar文件以及转换为exe可执行文件
- Java控制台程序如何在用户关闭时执行清理代码
- Java_Java项目如何生成可执行jar包、exe文件;
- Android java代码中如何执行shell命令
- 手把手教你如何把java代码,打包成jar文件以及转换为exe可执行文件
- 手把手教你如何把java代码,打包成jar文件以及转换为exe可执行文件
- 如何跟踪Java代码的执行
- 如何在java代码中调用一个web项目jsp或者servlet
- C# Javascript引擎,如何在C#中执行现有的Javacript代码?
- 手把手教你如何把java代码,打包成jar文件以及转换为exe可执行文件
- 如何将Java项目代码打包成exe文件
- 如何优化JAVA代码及提高执行效率
- 手把手教你如何把java代码,打包成jar文件以及转换为exe可执行文件
- 怎么用bat文件运行eclipse建立的项目,如何将写好的java项目生成可执行的bat文件
- 手把手教你如何把java代码,打包成jar文件以及转换为exe可执行文件