Java调用Python代码


今天学习了在Java程序中运行Python代码。

首先要导入依赖

<dependency>
       <groupId>org.pythongroupId>
       <artifactId>jython-standaloneartifactId>
       <version>2.7.2version>
dependency>
try {
            String[] str = new String[]{"python",
                    "*****count.py"};
            Process proc = Runtime.getRuntime().exec(str);      // 执行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();
        }

****count.py这里换成自己Python代码的路径

结果如图: