jythonDemo

1.pom文件引入jython包

<!-- jython -->
<dependency>
	<groupId>org.python</groupId>
	<artifactId>jython-standalone</artifactId>
	<version>2.7.1b3</version>
</dependency>
<!-- jython end -->

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值