JavaDemo——Java通过Jython调用py脚本

maven导入:


		
		    org.python
		    jython-standalone
		    2.7.2
		

准备python文件test2.py:

#!/usr/bin/env python3
# coding=utf-8

xyz='hello python'
abc=1234

class Result:
    s = ''
    r = 0.0
    def __init__(self, s, r):
        self.s = s
        self.r = r

def func_cls(x, y):
    print('py fun=x^2+2xy+y^2')
    print('x={0}, y={1}'.format(x, y))
    return Result('pyResult', eval('x**2 + 2*x*y + y**2'))

def func_str():
    return 'func2 return str'

def func_list():
    return [11, 22, 33]

def func_dict():
    return {1:'a', 2:'b', 3:'c'}

#没有变量newstr
def func_nostr():
    return newstr

if __name__ == '__main__':
    print('py main run')
#     func_nostr()#NameError: name 'newstr' is not defined

调用demo:

/**
 * 2020年7月6日上午10:16:29
 */
package testcallpython;

import org.python.core.PyDictionary;
import org.python.core.PyFloat;
import org.python.core.PyFunction;
import org.python.core.PyList;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;

/**
 * @author XWF
 *
 */
public class TestCallPython_Jython {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		PythonInterpreter interpreter = new PythonInterpreter();
		//执行python语句
		interpreter.exec("print('start test')");
		interpreter.exec("print('='*50)");
		
		//加载并运行python文件
		interpreter.execfile("src/testcallpython/test2.py");
		interpreter.exec("print('='*50)");
		
		//调用py文件里的属性
		PyObject xyzobj = interpreter.get("xyz");
		System.out.println("xyz=" + xyzobj);
		PyObject abcobj = interpreter.get("abc");
		System.out.println("abc=" + abcobj);
		interpreter.set("newstr", "newString");//手动添加newstr变量
		System.out.println("newstr=" + interpreter.get("newstr"));
		interpreter.exec("print('='*50)");
		
		//调用py文件里的方法
		PyFunction funcCls = interpreter.get("func_cls", PyFunction.class);
		PyObject returnPyobj = funcCls.__call__(new PyFloat(2), new PyFloat(3));
		System.out.println("结果:" + returnPyobj.toString());
		System.out.println("class=" + returnPyobj.getClass());
		System.out.println("s=" + returnPyobj.__findattr__("s"));
		System.out.println("r=" + returnPyobj.__findattr__("r"));
		System.out.println("ss=" + returnPyobj.__findattr__("ss"));
//		System.out.println(returnPyobj.__getattr__("ss"));//Exception in thread "main" AttributeError: Result instance has no attribute 'ss'
		interpreter.exec("print('='*50)");
		
		PyFunction funStr = interpreter.get("func_str", PyFunction.class);
		System.out.println(funStr.__call__().__tojava__(PyString.class));
		System.out.println(funStr.__call__());
		PyFunction funList = interpreter.get("func_list", PyFunction.class);
		PyList list = (PyList) funList.__call__().__tojava__(PyList.class);
		System.out.println(list);
		System.out.println(list.get(2));
		PyFunction funDict = interpreter.get("func_dict", PyFunction.class);
		PyDictionary dict = (PyDictionary) funDict.__call__().__tojava__(PyDictionary.class);
		System.out.println(dict);
		System.out.println(dict.get(2));
		
		PyFunction funcNostr = interpreter.get("func_nostr", PyFunction.class);
		System.out.println(funcNostr.__call__());//手动添加newstr后可以正常调用
	}
}

结果:

JavaDemo——Java通过Jython调用py脚本_第1张图片

有趣的是可以通过jython添加py里未定义的属性消除异常;

你可能感兴趣的:(JavaDemos,Jython)