最近需要使用java调python脚本,总结一下;
- 无参调用
如果要运行,都需要本地装python环境,尽量装python2.X版本,3.0貌似部分有改动(导致脚本运行不起来),装完python环境, 切入 CMD 输入python 即可测试下是否成功, 然后需要在你的eclipse 配置下 如图 (如果是应用服务器的话 在run connfig.. 中找到你运行的server ),
点击select 选出 path 即可(path中包含了 python的环境变量),
jython-standalone-2.7.0.jar 和jython-standalone-2.7.0源码 下载
// jython
PythonInterpreter interpreter = new PythonInterpreter();
log.info(" start exec ... ");
try {
interpreter.execfile("D:/haocs/hello.py");
} catch (Exception e) {
log.error("exec Exception ",e);
}
// java直接调用
private static final String PY_URL = "D:"+File.separator+"haocs"+File.separator+ "test.py";
public static void execPy() {
Process proc = null;
try {
proc = Runtime.getRuntime().exec("python " + PY_URL);
proc.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
- 有参且有返回值
// python 解释器 仅限于方法普通参数,如果python 参数是数组则运行不了
/**
* python 脚本如下
* def adder(a, b):
* return a + b
*/
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("D:\\haocs\\helloPython.py");
PyFunction func = (PyFunction) interpreter.get("adder",
PyFunction.class);
int a = 2010;
int b = 2;
PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));
System.out.println("result= " + pyobj.toString());
// jython 数组调用python
Properties props = new Properties();
props.put("python.console.encoding", "UTF-8");
props.put("python.security.respectJavaAccessibility", "false");
props.put("python.import.site", "false");
String[] arguments ={"127.0.0.1", "demo-server","start"};
PythonInterpreter.initialize(props,System.getProperties(), arguments);
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile(temp);
----------
// java 调用python 单个参数如下
// String cmd="python D:\\labs\\hello.py "+name+" "+path;
// Process pr = Runtime.getRuntime().exec(cmd);
//java 调用python 数组参数 ,
String[] args = new String[] { "python", "D:\\labs\\client.py","127.0.0.1","demo-server","start"};
//设置命令行传入参数
Process pr = Runtime.getRuntime().exec(args);
System.out.println(pr.toString());
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");