-1

I am working with a Python library but everything else is in Java. I want to be able to access and use the Python library from Java, so I started researching and using Jython. I need to use numpy and neurokit libraries.

I write this simple code in Java:

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.set("values", 10 );
interpreter.execfile("D:\\PyCharmWorkspace\\IoTproject\\Test.py");
PyObject b = interpreter.get("result");

and the code in Python:

import sys
sys.path.append("D:\\PyCharmWorkspace\\venv\\lib\\site-packages")
import numpy as np
result = values + 20

The problem is that when It tries to load module numpy, I get this error:

Exception in thread "main" Traceback (most recent call last):
  File "D:\PyCharmWorkspace\IoTproject\TestECGfeature.py", line 4, in <module>
    import numpy as np
  File "D:\PyCharmWorkspace\venv\lib\site-packages\numpy\__init__.py", line 142, in <module>
    from . import core
  File "D:\PyCharmWorkspace\venv\lib\site-packages\numpy\core\__init__.py", line 24, in <module>
    from . import multiarray
  File "D:\PyCharmWorkspace\venv\lib\site-packages\numpy\core\__init__.py", line 24, in <module>
    from . import multiarray
  File "D:\PyCharmWorkspace\venv\lib\site-packages\numpy\core\multiarray.py", line 14, in <module>
    from . import overrides
  File "D:\PyCharmWorkspace\venv\lib\site-packages\numpy\core\overrides.py", line 166
SyntaxError: unqualified exec is not allowed in function 'decorator' because it contains free variables

I also tried to do this:

    interpreter.exec("import sys");
    interpreter.exec("sys.path.append('D:\\PyCharmWorkspace\\venv\\lib\\site-packages')");
    interpreter.exec("import numpy as np");

and I get:

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

To install Jython I have add jar file to project build-path.

I found jep and jpy that can make communicate java with python but I didn't found how to install or use them.

What I need is call a Python function giving params and getting result. How Can I do or How can I solve the problem using Jython?

mzjn
  • 48,958
  • 13
  • 128
  • 248
  • NumPy does not work with Jython: https://scipy.org/scipylib/faq.html#does-numpy-scipy-work-with-jython-or-c-net. – mzjn Feb 16 '20 at 07:56
  • You might be able to use JyNI: https://www.jyni.org/. See also https://stackoverflow.com/a/30712675/407651 – mzjn Feb 16 '20 at 08:05

2 Answers2

0

Following code can be used for executing python script

   private void runPythonCode(String pythonScript) {
        ProcessBuilder pb = new ProcessBuilder("python", pythonScript);

    Process process = pb.start();
    int errCode = process.waitFor();

    if (errCode == 1) {
        System.out.println("Error");
    } else {
        String filePath = output(process.getInputStream());
        logger.info("Generated report file path ::" + filePath);
        if (filePath != null) {
            File docxFile = new File(filePath.trim());
            // creates a new file only if it does not exists,
            // file.exists() returns false
            // if we explicitly do not create file even if the file
            // exists
            docxFile.createNewFile();
            String updatedFileName = docxFile.getParent() + File.separator 
                    + jobAccountJson.getProviderName() + "_" + docxFile.getName();
            File reanmedFileName = new File(updatedFileName);
            if(docxFile.renameTo(reanmedFileName)) {
                logger.info("Renamed file to " + r

eanmedFileName.getPath());
                    return reanmedFileName;
                } else {
                    logger.error("Could not rename file to " + updatedFileName);
                }
                return docxFile;
            }
        }
}
private static String output(InputStream inputStream) throws IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line + System.getProperty("line.separator"));
        }
    } finally {
        if(br != null) {
            br.close();
        }
    }
    return sb.toString();
}
Komal Kadam
  • 808
  • 1
  • 7
  • 18
0
 ProcessBuilder pb = new ProcessBuilder("python", "NameOfScript.py");
 Process p = pb.start();
 p.getInputStream().transferTo(System.out);
jsnjdhs
  • 23
  • 7