zoukankan      html  css  js  c++  java
  • java调用python代码

    最近做项目时需要用Java调用python的文件,本篇博客介绍用java调用python的代码。

    一、使用Jpython来实现用java调用python的代码

      1.下载JPython的包

        我下载的是jython-2.7-b1.jar,下载好后在项目classpath中添加这个jar包。

      2.编写简易python代码

    import org.python.util.PythonInterpreter;
    import java.util.Properties;
    /**
    *@author chenmeiqi
    *@version 2020年2月26日 下午7:08:24
    */
    public class test {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            PythonInterpreter interpreter = new PythonInterpreter();
            // 运行python语句
            interpreter.exec("a = "hello, Jython"");
            interpreter.exec("print a");   
        }
    
    }

      运行结果:

      

     二、使用Runtime.getRuntime()执行脚本文件

      Runtime.getRuntime()可以取得当前JVM的运行时环境,这也是在java中唯一一个得到运行时环境的方法。

      注:如果执行的Python脚本有引用第三方包的,建议使用此种方式。

      代码示例:

    import org.python.util.PythonInterpreter;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Properties;
    /**
    *@author chenmeiqi
    *@version 2020年2月26日 下午7:08:24
    */
    public class test {
    
        public static void main(String[] args) throws IOException, InterruptedException {
            // TODO Auto-generated method stub
                    Process proc = Runtime.getRuntime().exec("D:\Anaconda3\envs\py36\python.exe D:/spider/ItemCF.py");
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            proc.waitFor();
            System.out.println("end"); 
        }
    
    }

      python脚本代码:

    print("使用java调用python代码!")

      运行结果:

      

  • 相关阅读:
    人工智能数学基础笔记(上)
    人工智能简介
    十三,十四 基金收益,税收与基金国际化
    资产配置模型之-BL模型
    十二 基金估值,费用与会计核算
    十一 基金的投资交易与结算
    十 基金业绩评价
    九 投资风险管理
    浙工商oj ___飞龙的飞行方程
    hd1004解题思路
  • 原文地址:https://www.cnblogs.com/qilin20/p/12369056.html
Copyright © 2011-2022 走看看