当前位置:Gxlcms > Python > JAVA调python脚本

JAVA调python脚本

时间:2021-07-01 10:21:17 帮助过:67人阅读

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try {
System.out.println("start");
Process pr = Runtime.getRuntime().exec("python test.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();
}
}
}
如果在eclipse中直接运行报如下错误:
java.io.IOException: Cannot run program "python": CreateProcess error=2
则配置Run Configuration中的Enviroment,增加PATH变量,见附件:

在java application中调用Process proc = Runtime.getRuntime().exec("python xx.py");是可以的【xx.py直接位于工程目录下面】

在tomcat中的servlet中使用Process proc = Runtime.getRuntime().exec("python xx.py");时,开始是没反应。 排查结果应该是pyhon命令可以找到(或者直接输入e:\\Python\\python.exe绝对路径) x.x.py 文件我是放在根目录下,故意把名字写错成xy.py.,结果都是没反应【仿佛这条语句没有执行】
=》应该是py文件找不到。我用了绝对路径搜索py文件。Process proc = Runtime.getRuntime().exec("python d:\\xx.py");这个倒是可以。
【目前总结 就是py文件的路径问题】

人气教程排行