JAVA执行python的方法万能工具

这个脚本的好处就是提供了一个工具JAVA执行python的方法,但这种方式不支持python3,只支持python2。我是小順,请大家关注我,我会给大家发更多的工具。

python程序:

# -*- coding: utf-8 -*-

def add(strr):
     return strr;
     
import math   
def add2(num1,num2,strr):
    s = math.sqrt(num1)+math.sqrt(num2);
    strr = str(s)+"hello";
    return strr;

prop.properties配置文件:

URL=E:\\workspace\\testP\\src\\com\\edu

JAVA程序:

package com.edu;

import java.io.InputStream;
import java.util.Properties;
import org.junit.Test;
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.jline.internal.InputStreamReader;
import org.python.util.PythonInterpreter;



public class JavaExecutePython {
    
    private static String url;
    
   //=======================================================================================
   /**
    * 准备URL
    * Prepare URL
    * 
    * @param URL=E:\\workspace\\testP\\src\\com\\edu
    * @return E:\workspace\testP\src\com\edu
    */
    public static String prepareUrl(String properties){
        //获取路径 Get path
        url = "";
        InputStream in = null;
        try {
            //创建Properties对象  Create a Properties object
            Properties prop = new Properties();
            //读取属性文件prop.properties Read the property file prop.properties)
            in = JavaExecutePython.class.getResourceAsStream(properties);
            //加载属性列表  Load attribute list
            prop.load(new InputStreamReader(in, "utf-8"));
            //读取属性列表  Read attribute list
            url = prop.getProperty("URL");
            /**
             * 组合地址  
             * Combined address
             */
            String[] urlString = url.split("\\\\");
            String urlTemp = "";
            for (String s : urlString) {
                urlTemp = urlTemp + s + "\\\\";
            }
            url = urlTemp + "sqrt.py";
            return url;
  
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
        
    }
    //=======================================================================================
    /**
     * 准备执行
     * prepare execute
     * @param url
     * @param method
     * @return
     */
    public static PyFunction prepareExecute(String url,String method){
        /**
         * jyphon 环境变量配置
         * Jyphon environment variable configuration
         */
        System.setProperty("python.console.encoding", "utf-8");
        /**
         * 创建python解析器
         * Create a python parser
         */
        PythonInterpreter interp =  new PythonInterpreter();
        /**
         * 执行py文件
         * Execute the py file (preferably a py one method)
         */
        interp.execfile(url);
        /**
         * 调用py中的方法
         * Call the method in py
         */
        PyFunction function = (PyFunction)interp.get(method,PyFunction.class); 
        /**
         * 返回结果
         * Return result 
         */
        return function;   
    }
    //===========这一步我用的是JUNITE测试,也可以用main函数测试===================================================
    /**
     * 如何使用该方法
     * How to use this method
     */
    @Test
    public void test(){
        /**
         * 准备url 
         * prepare url
         */
        url = prepareUrl("prop.properties");
        /**
         * 准备执行 方法
         * prepare Call method
         */
        PyFunction function1 = prepareExecute(url,"add2");
        PyFunction function2 = prepareExecute(url,"add");
        /**
         * 执行方法
         * call method
         */
        PyObject o1 = function1.__call__(new PyInteger(25),new PyInteger(25),new PyString("hello"));
        PyObject o2 = function2.__call__(new PyString("hello"));
        /**
         * 转成String
         * transfer string
         */
        String result1 = o1.toString();
        String result2 = o2.toString();
        /**
         * 使用该结果
         * use result
         */
        System.out.println("result1:"+result1);
        System.out.println("result2:"+result2);
    }
}

猜你喜欢

转载自blog.csdn.net/walteryonng20xx/article/details/84786425