jythonDemo

1.pom文件引入jython包



	org.python
	jython-standalone
	2.7.1b3


2.新建一个java接口类

package com.yinzhen.demo.service;

public interface PythonInterfaceDemo {

	String hello(String string);

}

3.使用python实现这个接口类,并初始化一个实例在D盘新建一个test.py

#!/usr/bin/python3

from com.yinzhen.demo.service import PythonInterfaceDemo


class PythonInterfaceDemoImpl(PythonInterfaceDemo):
    def __init__(self):
        '''''public MyDerive()'''
        pass
        
    def hello(self,name):
        return "hello" + name;
        
pythonInterfaceDemo = PythonInterfaceDemoImpl() 

4.通过java调用python的代码

package com.yinzhen.demo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import org.python.core.PyException;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yinzhen.demo.service.PythonInterfaceDemo;


public class DemoApplication {
     
	
	private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class);
	private static PythonInterfaceDemo pythonInterfaceDemo = null;

	public static void main(String[] args) throws Exception {
     
		
		//加载python文件
		initLoadPythonFile();
		
		//执行python脚本问好
		String returnHello = pythonInterfaceDemo.hello("yinzhen");
		System.out.println(returnHello);
	}

	private static void initLoadPythonFile() throws Exception {
     
		Reader in = null;
		PythonInterpreter interpreter = new PythonInterpreter();
		try{
     
			File file = new File("D://test.py");
            in = new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8"),1024*2048);
            in.mark(1024*1024);
            PyObject code = interpreter.compile(in); 
            interpreter.exec(code);
            pythonInterfaceDemo = (PythonInterfaceDemo)interpreter.get("pythonInterfaceDemo", PythonInterfaceDemo.class);
            if(pythonInterfaceDemo == null){
     
              interpreter.close();
              throw new Exception("no deri instance in script file");  
            }
        }catch(PyException e){
     
            logger.error(e.toString());
            logger.error(e.getMessage(),e);
            throw e;
        }catch(IOException e){
     
            logger.error(e.getMessage(),e);
            throw e;
        }finally {
     
        	in.close();
            interpreter.close(); 
        }
	}
}

5.配置java参数,如果不配置执行时会报错

Dpython.console.encoding=UTF-8

你可能感兴趣的:(java)