00-java调用python脚本

1 创建maven项目

在pom.xml文件中添加相应库:

   

        org.python

        jython-standalone

        2.7.0

   

   

   

        commons-beanutils

        commons-beanutils

        1.9.3

   

   

        commons-collections

        commons-collections

        3.2.1

   

   

        commons-lang

        commons-lang

        2.6

   

   

        commons-logging

        commons-logging

        1.1.1

   

   

        net.sf.ezmorph

        ezmorph

        1.0.6

   

   

        net.sf.json-lib

        json-lib

        2.2.3

        jdk15

   

   

2 创建ok.py文件,该文件位置需要直接放置在项目目录中

#-*- coding: UTF-8 -*-

import json

def hello(x):

    y=json.loads(x)

    return r'{k1:"成功没有%d", str:"%s"}'%(y["xid"],y["xname"])

3 创建java调用代码

import net.sf.json.JSONObject;

import org.python.core.*;

import org.python.util.PythonInterpreter;

public class ok {

    //调用python语句

    public void py01(){

        PythonInterpreter interpreter = new PythonInterpreter();

        interpreter.exec("print('hello')");

    }

//    调用python脚本

    public void py02(){

        PythonInterpreter interpreter = new PythonInterpreter();

        interpreter.execfile("ok.py");

        PyFunction pyFunction = interpreter.get("hello", PyFunction.class); // 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型

        String s="{\"xid\":18,\"xname\":\"你好\"}";

        PyString str = Py.newStringUTF8(s);

        PyObject pyObject = pyFunction.__call__(str); // 调用函数

        JSONObject obj=new JSONObject();

        System.out.println(pyObject);

    }

    public static void main(String[] args) {

        ok k=new ok();

        k.py02();

    }

}

执行返回结果:

{k1:"æ��å��没æ��18", str:"你好"}

你可能感兴趣的:(00-java调用python脚本)