Java调用python,并且选择python环境

项目场景:

当我们使用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();
        }
    }
}

这样就完美解决

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值