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.

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

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.