1

I have created an PythonInterpreter object, and want to call a java function but keep getting the error:

Exception in thread "main" Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'jytest2' is not defined
Java Result: 1

How do you call a java function from a live running system?

public static void main(String args[])
    {      
        ModRet modRet = new ModRet();
        jytest();
    }

public void jytest()
    {
        PythonInterpreter interp = new PythonInterpreter();

        interp.exec("print \'Hello; jython has successfully been embedded!\'");
        interp.exec("print " + FPS);
        interp.exec("jytest2()");

    }

    public void jytest2()
    {
        System.out.println("HIHIHI");
    }
3
  • It'd be really helpful if you could post some of the relevant Jython code Commented May 12, 2011 at 20:13
  • I did find one way to accomplish this: by running the constructor in jython. But is there another way? Commented May 12, 2011 at 20:17
  • The interp.exec(String) will only interpret in Python/Jython language; did you have the Python function jytest2() created for interpretation? That is what I can understand from the error message as it could not find the function...You may need to import from a library that has the function first before you can use it. Commented May 13, 2011 at 1:28

2 Answers 2

1

I generally find that I need to use the Object Factory pattern and invoke things via an Interface as described in the Jython Book - Chapter 10

I'm still not super-clear on what you're trying to accomplish, so I don't have any code for you; but I'm sure you'll find the book helpful.

Sign up to request clarification or add additional context in comments.

Comments

1

By default, the current classpath is included in jython path. To access any method in the path, you should do an import.

package com.mycompany.jythontest;


import org.python.util.PythonInterpreter;


public class App 
{

  public static void sayHello(String hello) {
    System.out.println(hello);
  }

  public static void main( String[] args )
  {
      PythonInterpreter py = new PythonInterpreter();

      py.exec("from com.mycompany.jythontest import App");
      py.exec("App.sayHello('hello')");
  }
}

And if you want to access a java instance in jython, you can use py.set(string, object) to make it accessible in the context. (Just like javax.scripting)

      App app = new App();
      py.set("appinstance", app);
      py.exec("appinstance.sayHi('hello world')");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.