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

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();
        }
    }
}