【问题标题】:Execute python function from Java code and get result从 Java 代码执行 python 函数并获取结果
【发布时间】:2020-02-11 15:09:59
【问题描述】:

我正在使用 Python 库,但其他一切都在 Java 中。 我希望能够从 Java 访问和使用 Python 库,所以我开始研究和使用 Jython。我需要使用 numpy 和 neurokit 库。

我用 Java 编写了这个简单的代码:

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

以及 Python 中的代码:

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

问题是当它尝试加载模块 numpy 时,我收到此错误:

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

我也尝试过这样做:

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

我得到:

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

要安装 Jython,我已将 jar 文件添加到项目构建路径。

我找到了 jep 和 jpy 可以使 java 与 python 通信,但我没有找到如何安装或使用它们。

我需要的是调用一个 Python 函数来提供参数并获得结果。 我该怎么做或如何使用 Jython 解决问题?

【问题讨论】:

标签: java python numpy jython


【解决方案1】:

以下代码可用于执行python脚本

   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();
}

【讨论】:

  • 你能解释一下解决方案吗,OP的代码有什么问题?
猜你喜欢
  • 2013-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-31
相关资源
最近更新 更多