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

maven导入:

<!-- https://mvnrepository.com/artifact/org.python/jython-standalone -->
		<dependency>
		    <groupId>org.python</groupId>
		    <artifactId>jython-standalone</artifactId>
		    <version>2.7.2</version>
		</dependency>

准备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后可以正常调用
	}
}

结果:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值