how to add module of python into java using jython jar

放肆的年华 提交于 2019-12-08 08:15:02

问题


I used Netbeans platform to build my application uasing java languge.I need to invoke some python functions into java class using jython was the only way. unfortunatly when I tried to run the program an error showed indicate that the application did not find the following modules

Exception in thread "main" Traceback (most recent call last):

File "script.py", line 13, in <module>
    import re
ImportError: No module named re
  File "script.py", line 14, in <module>
    from string import *
ImportError: No module named string
Java Result: 1 

this is the code in script.py that I want to invoke one of it's method into my java class

#!/pkg/ldc/bin/python2.1

import xml.parsers.expat
import re
from string import *
import sys

How to add these python modules into my application ?


回答1:


The following code runs just fine on my Ubuntu box with Jython 2.7 and Java 1.6 (tested with Eclipse and from the terminal):

package myjythonproject;
import org.python.util.PythonInterpreter;

public class MyJythonProject {

    public static void main(String[] args) {
        try
        {
            PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
            PythonInterpreter interp = new PythonInterpreter();
            interp.execfile("/home/vicent/foo.py");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Just make sure to compile and execute with jython.jar in your classpath.

UPDATE

I've just installed NetBeans 7.2.1 (version for Java SE) on my Ubuntu box, created a new Java project, MyJythonProject, and added the code shown above to the MyJythonProject.java file. Then on the Properties dialog of the project I've selected Libraries in the left pane. In the right pane I've selected the Compile tab, clicked the Add JARF/folder button and selected my jython jar (/opt/jython2.7a2/jython.jar). The I've closed the Dialog and in the Run menu of the main window I've selected Clean and Build Project (MyJythonProject). After that I've run the project and it works like a charm. No Python/Jython plugin required, just tell to your project where the jython.jar is installed.

UPDATE 2

Also notice that Python3 is not supported by Jython so you have to use a Python2.x interpreter.



来源:https://stackoverflow.com/questions/14020382/how-to-add-module-of-python-into-java-using-jython-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!