Search code examples
javapythonjythonjython-2.7

Run a python function with arguments from java using jython


I want to execute a Python function which is located in one of my python projects from java by using jython. https://smartbear.com/blog/test-and-monitor/embedding-jython-in-java-applications/ is giving the sample code for the purpose. But in my scenario I got the following exception.

Exception in thread "main" Traceback (most recent call last): File "", line 1, in ImportError: No module named JythonTestModule

My scenario is as follows.

  1. I have created a python module inside my python project(pythonDev) by using PyCharm(JythonTestModule.py) which contains the following function.

    def square(value): return value*value

  2. Then I created a sample java class in my java project(javaDev) and called the python module.

    public static void main(String[] args) throws PyException{
       PythonInterpreter pi = new PythonInterpreter();
       pi.exec("from JythonTestModule import square");
       pi.set("integer", new PyInteger(42));
       pi.exec("result = square(integer)");
       pi.exec("print(result)");
       PyInteger result = (PyInteger)pi.get("result");
       System.out.println("result: "+ result.asInt());
       PyFunction pf = (PyFunction)pi.get("square");
       System.out.println(pf.__call__(new PyInteger(5)));
    }     
    

    After running this java method the aforementioned exception is generated by the java program. I want to know what is the problem with this menioned code segments.


Solution

  • As from the suggestions from the above comments section of this question, I have developed the solution to my question. Following code segment will demonstrate that. In this solution I have set the python.path as the directory path to my module file.

    public static void main(String[] args) throws PyException{
           Properties properties = new Properties();
           properties.setProperty("python.path", "/path/to/the/module/directory");
           PythonInterpreter.initialize(System.getProperties(), properties, new String[]{""});
           PythonInterpreter pi = new PythonInterpreter();
           pi.exec("from JythonTestModule import square");
           pi.set("integer", new PyInteger(42));
           pi.exec("result = square(integer)");
           pi.exec("print(result)");
           PyInteger result = (PyInteger)pi.get("result");
           System.out.println("result: "+ result.asInt());
           PyFunction pf = (PyFunction)pi.get("square");
           System.out.println(pf.__call__(new PyInteger(5)));
        }
    

    If you want to use multiple modules from the Jython, add the python.path as the parent directory path of all the modules in order to detect all the modules.