在网上有很多方法来解决python文件找不到包的方法,我也试了试,但是不尽人意,于是脑洞大开尝试将python脚本编译为exe,再从java 中调用执行exe文件,并获取控制台输出流,获取输出文本。特此记录。(需要其他包来支持py文件的情况)
补充:在慕课高阶java编程课程中,了解到更轻便的方法,直接执行py文件(前提:无需导入其他库文件或者包)
可能我也有一些理解不当的地方,欢迎大家补充纠正!
部分代码:
@SuppressWarnings("resource")
public void Spider() {
String[] pra = { "", "", "", "" };
try {
String pythonFile = System.getProperty("user.dir") + "\\src\\Weather\\test.exe";
pra[0] = pythonFile;
String[] paramter = new String[] { pra[0] }; // 这里可以设置传入参数 pra[1] 等等,加入paramter 即可
Process pr = Runtime.getRuntime().exec(paramter);
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String call;
int i = 0;
while ((call = in.readLine()) != null) {
this.info[i] = call;
i++;
}
in.close();
pr.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}