这篇博客主要记录的是使用命令行调用python。在命令行调用python文件过程中,如果python文件中包含了很多其他的python的库,就可能会在运行的时候出现No model named XX的错误。如果你的程序在pycharm中运行没有问题的话,可以按照下面方式来写。
1.首先建立一个系统环境变量anacoda(后面可以通过java代码自动获取到这个路径) ,里面的值填入你的anaconda下面这个scripts目录的路径
2.在java代码中获取到anaconda的路径并对格式进行转换
String condaPath = System.getenv("anaconda");
condaPath =condaPath.replace("\\","\\\\");
3.调用runtime方法执行,这里需要执行两条命令,使用的&&连接(要使用conda环境也主要是第一条命令,即执行anaconda scripts文件夹下的activate.bat文件)我这里的python文件的路径也是提前获取的,读者可以根据需要直接指定具体的路径。注意斜杠符号,不要出错即可
Process process = Runtime.getRuntime().exec(condaPath+"\\activate.bat && python "+path+"tree.py");
4.读取结果,可以将错误流的内容也读取出来
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
in = new BufferedReader(new InputStreamReader(process.getInputStream(),"gbk"));
//接收错误流
BufferedReader isError = new BufferedReader(new InputStreamReader(process.getErrorStream(),"gbk"));
StringBuilder sb= new StringBuilder();
StringBuilder sbError= new StringBuilder();
String line=null;
String lineError= null;
while ((line = in.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
System.out.println(sb);
while ((lineError= isError.readLine()) != null) {
sbError.append(lineError);
sbError.append("\n");
}
System.out.println(sbError);
全部代码:
String path = System.getProperty("user.dir")+"\\src\\main\\java\\python\\";//获取到项目目录后,补充完整python文件所在目录
path =path.replace("\\","\\\\");
String condaPath = System.getenv("anaconda");//获取conda的系统变量
condaPath =condaPath.replace("\\","\\\\");
System.out.println(condaPath);
Process process = Runtime.getRuntime().exec(condaPath+"\\activate.bat && python "+path+"tree.py");
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
in = new BufferedReader(new InputStreamReader(process.getInputStream(),"gbk"));
//接收错误流
BufferedReader isError = new BufferedReader(new InputStreamReader(process.getErrorStream(),"gbk"));
StringBuilder sb= new StringBuilder();
StringBuilder sbError= new StringBuilder();
String line=null;
String lineError= null;
while ((line = in.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
System.out.println(sb);
while ((lineError= isError.readLine()) != null) {
sbError.append(lineError);
sbError.append("\n");
}
System.out.println(sbError);
in.close();
isError.close();
return sb.toString();