您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

从JAR中执行python文件

从JAR中执行python文件

使用开头的文件路径/意味着您要从文件系统的根目录开始。

您的代码为我工作,只需删除该斜杠即可:

public static void main(String[] args) {
    try {
        File python = new File("scripts/script.py");
        System.out.println(python.exists()); // true

        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec("python scripts/script.py"); // print('Hello!')

        BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String line = "";
        while((line = bfr.readLine()) != null)
            System.out.println(line);
    }
    catch(Exception e) {
        System.out.println(e.toString());
    }
}

// true
// Hello!
// Process finished with exit code 0

放置错误文件没有显示错误的原因是因为此Java代码显示输入流(getInputStream()),而不显示错误流(getErrorStream()):

    public static void main(String[] args) {
    try {
        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec("python scripts/doesnotexist.py");

        BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
        String line = "";
        while((line = bfr.readLine()) != null)
            System.out.println(line);
    }
    catch(Exception e) {
        System.out.println(e.toString());
    }
}

// python: can't open file 'scripts/doesnotexist.py': [Errno 2] No such file or directory
// Process finished with exit code 0
python 2022/1/1 18:35:02 有230人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶