项目场景:
当我们使用anaconda时,java调用cmd来执行python,默认是base环境,该怎么切换环境?
问题描述
不切换环境,会出现报错,是每个环境所下载的包都不同,导致的。
public class Test {
public static void main(String[] args) {
try {
String[] params = {
"python",
"main.py"
};
Process process = Runtime.getRuntime().exec(
params
);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
System.out.println(process.waitFor());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
当我们直接运行时,会报错,是因为没有调用对应环境的python,这个环境不存在这个包
原因分析:
调用不到python,我们在cmd上也是默认调用conda的base环境的,要调用其他的环境,一种是设置环境变量,另一种是直接切换到python环境目录下执行,就可以使用这个环境,我这里推荐第二种,比较方便,如果一直要调用不同环境的python,就需要该环境变量,所以推荐第二种。
解决方案:
我们在执行python的命令时,可以带上路径,就可以完美解决
public class Test {
public static void main(String[] args) {
try {
String[] params = {
// 这里直接加上路径 路径\\python 就可以了
"D:\Anaconda\anaconda3-2019\\envs\\test\\python",
"main.py"
};
Process process = Runtime.getRuntime().exec(
params
);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
System.out.println(process.waitFor());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
这样就完美解决