1

I am trying to develop a simple Java application and I want it to use some Python code using Jython. I am trying to run a python method from a file and getting this error:

ImportError: cannot import name testFunction

Just trying a simple example so I can see where the problem is. My python file test.py is like this:

def testFunction():
    print("testing")

And my Java class:

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("path_to_file\\test.py");

interpreter.exec("from test import testFunction");

So it can correctly find the module but behaves like there is no function called testFunction inside.

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58

1 Answers1

1

Execute script files as follows.

interpreter.execfile("path/to/file/test.py");

If you have functions declared in the script file then after executing the above statement you'll have those functions available to be executed from the program as follows.

interpreter.exec("testFunction()");

So, you don't need to have any import statement.

Complete Sample Code:

package jython_tests;

import org.python.util.PythonInterpreter;

public class RunJythonScript2 {
    public static void main(String[] args) {
        try (PythonInterpreter pyInterp = new PythonInterpreter()) {
            pyInterp.execfile("scripts/test.py");
            pyInterp.exec("testFunction()");
        }
    }
}

Script:

def testFunction():
    print "testing"

Output:

testing
Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58