Java调用Python脚本工具类
[本文出自天外归云的博客园]
在网上查了很多方法都不成功,在google上搜到一篇文章,做了一些小修改,能够处理中文输出。提取一个运行python脚本的Java工具类如下:
package com.autox.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class RunPython { public static ArrayList<String> run_py(String script) { String s = null; ArrayList<String> result = new ArrayList<String>(); ArrayList<String> error = new ArrayList<String>(); try { Process p = Runtime.getRuntime().exec(script); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream(), "GBK")); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((s = stdInput.readLine()) != null) { result.add(s); } while ((s = stdError.readLine()) != null) { error.add(s); } if (error != null) { System.out.println(error); } } catch (IOException e) { e.printStackTrace(); } return result; } }
Java中调用方法如下:
ArrayList<String> result = RunPython.run_py("python script_path args"); for (String item : result) { System.out.println(item); }
其中script_path需替换为Python脚本路径,args替换为向脚本传递的参数。
本文来自博客园,作者:天外归云,转载请注明原文链接:https://www.cnblogs.com/LanTianYou/p/6635386.html