java.io.IOException: Cannot run program “python“: CreateProcess error=2, 系统找不到指定的文件。

本文介绍了一种在Java中通过使用Python的绝对路径来调用Python脚本的方法,解决了因系统未找到指定文件而导致的IOException问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java.io.IOException: Cannot run program “python”: CreateProcess error=2, 系统找不到指定的文件。

原因: python 这个命令 用java运行没有找到

解决:直接改用python.exe这个文件的绝对路径

错误源代码

public class Test {
    public static void main(String[] args) {
        Process proc;
        try {
            proc = Runtime.getRuntime().exec("python C:\\Users\\Administrator\\Desktop\\javapydemo\\src\\main\\java\\com\\example\\javapydemo\\demo\\main.py");//执行Py文件
            //用输入输出流来截取结果
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            proc.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

修改后源代码

public class Test {
    public static void main(String[] args) {
        Process proc;
        try {
            proc = Runtime.getRuntime().exec("C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\python.exe C:\\Users\\Administrator\\Desktop\\javapydemo\\src\\main\\java\\com\\example\\javapydemo\\demo\\main.py");//执行Py文件
            //用输入输出流来截取结果
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            proc.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值