1、首先确定python程序的路径pathPython
2、确定python 的scripts的路径找到activate.bat,在此路径下cmd,用于找到conda的基础环境(base)
3、定位到含有.conda文件下的C盘(我的是C:\Users\pc)
4、此时已经是conda的环境下了,再激活对应的pytorch库
5、运行python 程序
6、代码解析
主要是Process process = Runtime.getRuntime().exec("…………………………………………");代码来实现
省略号,是cmd Windows 命令提示符内要走的过程,每步用&&隔开,如下:
condaPath+"\\activate.bat && C: && conda activate pytorch && python "+path+"donghua_FDD_2.py"
其他部分的代码用于接收数据、接收python控制台的内容(下面那些Loss),可根据需要删减
String path ="D:\\python_dcgan\\python1\\dcgan\\";//获取到项目目录后,补充完整python文件所在目录
path =path.replace("\\","\\\\");
String condaPath = "D:\\python\\Scripts";//获取conda的系统变量
System.out.println(condaPath);
Process process = Runtime.getRuntime().exec(condaPath+"\\activate.bat && C: && conda activate pytorch && python "+path+"donghua_FDD_2.py");
int re=process.waitFor();//re=0成功,re=1失败
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;
process.waitFor();
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();