Hi,

 

This might be a silly question – never used Jython before – but how would I go about using Python modules in a Java application?

 

Well, this warrants a little more explanation. :)

 

So, I am toying around with a simple MUD server. Now, my idea was to use a scripting language to define behaviours of different items, so that I can update those behaviours, and even add new ones, all without ever stopping the server – which is written in Java.

 

Now, I don’t know what’s the best way to do it – any hints about this are certainly welcome, too :) – but my solution was that I would basically have an Item class, and then I would have a bunch of Python subclasses of item, all overriding a function which gets invoked when the user wants to use the item. But the problem I am having is – I am not sure how to actually now use the Python class? The Java code can detect when the user wants to use the item, but I am not sure how to actually invoke the Python function?

 

I looked around the net, and found this resource here:

 

http://www.samspublishing.com/articles/article.asp?p=26127&seqNum=6

 

And that says that I need to call __builtin__.__import__, and give it the name of the module I want to import… But it always returns null… I wrote a simple test program to try it out. Basically, the structure is like this:

 

d Project

|

+-JythonTest.java

|

+-pythontest.py

|
+-__init__.py

 

pythontest.py simply contains some functions I could call to see if the module got loaded. And then, inside the Java file, I have:

 

import org.python.core.*;

import org.python.util.*;

 

public class JythonTest {

  public static final void main(String[] agrs) {

            //Before we can import stuff, we need to initialize the interpreter:

            PythonInterpreter.initialize(System.getProperties(),

                                                                                                 null,

                                                                                                 new String[0]);

 

//Right so first we would like to import the test module...

            PyModule testModule = (PyModule) __builtin__.__import__("pythontest");

 

            if (testModule == null) {

              throw new NullPointerException("Object returned by  __builtin__.__import__ is null...");

            }

 

            //Next, let's try and call the testfunc:

            testModule.invoke("testfunc");

  }

}

 

Well, what happens when I compile and run that, is that the null pointer exception always gets thrown – the __import__ method returns null…

 

If anyone could tell me what I’m doing wrong here, I’d much obliged. :)

 

TIA,

Vovan