1. 程式人生 > >JAVA執行python的方法萬能工具

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