java 调用python的工具类

来源:互联网 发布:java jar 指定main 编辑:程序博客网 时间:2024/06/18 02:40
</pre><pre name="code" class="java">package pythonUtil;/*** *   pythonUtil 需要先导入相应的jpython jar 包   */import javax.script.*;import org.python.util.*;import java.io.*;import org.python.core.*;import static java.lang.System.*;public class pythonUtil {/** * 在python解释器中 执行一行命令 *  * @param order * 执行的命令 例子:num=('1','2','3','4','5','6','7'); */public static void orderLine(String order) {PythonInterpreter interpreter = new PythonInterpreter();interpreter.exec(order);}/** *  * @param fileName *            要执行python文件 绝对路径 * @param functionName *            要执行的函数 * @param param1 *            整形参数1 * @param param2 *            整形参数2 */public static void exeFunction(String fileName, String functionName,int param1, int param2) {PythonInterpreter interpreter = new PythonInterpreter();interpreter.execfile(fileName);PyFunction func = (PyFunction) interpreter.get(functionName,PyFunction.class);PyObject pyobj = func.__call__(new PyInteger(param1), new PyInteger(param2));System.out.println(pyobj.toString());}/** *  * @param fileName *            要执行python文件 绝对路径 * @param functionName *            要执行的函数 * @param param1 *            字符串参数 */public static void exeFunction(String fileName, String functionName,String param1) {PythonInterpreter interpreter = new PythonInterpreter();interpreter.execfile(fileName);PyFunction func = (PyFunction) interpreter.get(functionName,PyFunction.class);PyObject pyobj = func.__call__(new PyString(param1));System.out.println(pyobj.toString());}/** * 执行python script *  * @param fileName *            绝对路径 */public static void exeScript(String fileName) {PythonInterpreter interpreter = new PythonInterpreter();interpreter.execfile(fileName);}/** * 利用JAVA中的Runtime来执行python文件 * @param 要执行的文件命令 */public static void RuntimeExePython(String order) {try {System.out.println("Execute Python File ");Process pr = Runtime.getRuntime().exec(order);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("Python File End");} catch (Exception e) {e.printStackTrace();}}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stuborderLine("print 1;");exeFunction("D:\\java语言编程程序\\python\\add.py", "add", 1, 2);exeFunction("D:\\java语言编程程序\\python\\add.py", "a", "hello world!");exeScript("D:\\java语言编程程序\\python\\add.py");RuntimeExePython("python add.py");}}


0 0