Jython调用不包含第三方库的python脚本

来源:互联网 发布:泡泡堂 mac 编辑:程序博客网 时间:2024/05/18 17:28

1、本地环境安装的是Python 2.7.11

2、用maven下载jython依赖

  1. <pre name="code" class="html"><dependency>  
  2.     <groupId>org.python</groupId>  
  3.     <artifactId>jython</artifactId>  
  4.     <version>2.7.0</version>  
  5. </dependency>  
3、python脚本编写
  1. #coding:utf-8  
  2.   
  3. def adder(a, b):    
  4.    return a + b   
  5.   
  6. def mytest(str2):  
  7.     print str2  
  8.     return 'call success !!!'  

4、Java调用Python 
  1. <pre name="code" class="java">package test1;  
  2.   
  3. import java.util.Properties;  
  4.   
  5. import org.python.core.PyFunction;  
  6. import org.python.core.PyInteger;  
  7. import org.python.core.PyObject;  
  8. import org.python.core.PyString;  
  9. import org.python.util.PythonInterpreter;  
  10.   
  11. public class Java2Python {  
  12.     public static void main(String args[]) {  
  13.         Properties props = new Properties();  
  14.         props.put("python.home","D:/Python27/Lib");  
  15.         props.put("python.console.encoding""UTF-8"); // Used to prevent: console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.  
  16.         props.put("python.security.respectJavaAccessibility""false"); //don't respect java accessibility, so that we can access protected members on subclasses  
  17.         props.put("python.import.site","false");  
  18.         Properties preprops = System.getProperties();  
  19.         PythonInterpreter.initialize(preprops, props, new String[0]);  
  20.           
  21.         PythonInterpreter interpreter = new PythonInterpreter();  
  22.   
  23.         interpreter.execfile("E:/workspace3/test1/src/main/java/test1/my_utils.py");  
  24.         PyFunction adder = (PyFunction) interpreter.get("adder", PyFunction.class);  
  25.   
  26.         int a = 30, b = 50;  
  27.         PyObject pyobj = adder.__call__(new PyInteger(a), new PyInteger(b));  
  28.         System.out.println("anwser = " + pyobj.toString());  
  29.         PyFunction mytest = (PyFunction) interpreter.get("mytest", PyFunction.class);  
  30.         PyObject pyobj2 = mytest.__call__(new PyString("this is java project!!!"));  
  31.         System.out.println(pyobj2.toString());  
  32.         interpreter.close();  
  33.   
  34.     }  
  35. }  

以上方式可以实现Java调用Python,但是在python 脚本中只能有python的原生api,如果在在脚本中有引入pandas,numpy之类的第三方扩展包,还是会是会找不到,这个问题正在查找是什么原因..

 numpy , scipy 都是 c python 的第三方模块,是用 c (部分 c++, 和 fortran )写的,必然不支持

原创粉丝点击