1.Java与Python混合开发
- 我熟练使用的语言是java,java与python的混合开发怎么实现,javaEE+python来实现在线测试工具。以下是一个简单思路的整理。
<dependency> <groupId>org.python</groupId> <artifactId>jython-standalone</artifactId> <version>2.7.0</version> </dependency>
public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); PythonInterpreter interpreter = new PythonInterpreter(); interpreter.exec("a=[5,4,3,2,1]"); interpreter.exec("print sorted(a)"); } }
- 上面的方法过于繁琐,可以直接引入py文件
def add(a,b): return a+b if __name__ == '__main__': print add(1,2)
package com.firewolf; import org.python.core.PyFunction; import org.python.core.PyInteger; import org.python.core.PyObject; import org.python.util.PythonInterpreter; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); PythonInterpreter interpreter = new PythonInterpreter(); interpreter.exec("a=[5,4,3,2,1]"); interpreter.exec("print sorted(a)"); interpreter.execfile("src/resources/AddTwoNum.py"); PyFunction function = interpreter.get("add",PyFunction.class); //如果有main方法回执信main方法。 int a = 1,b=2; System.out.println("调用py"); PyObject pyObject = function.__call__(new PyInteger(a),new PyInteger(2)); System.out.println("add的答案是"+pyObject); } }
本文摘自 :https://blog.51cto.com/u