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

Java调用Python脚本工具类

2017-03-28 16:16 731 查看
[本文出自天外归云的博客园]

在网上查了很多方法都不成功,在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替换为向脚本传递的参数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: