我试图从捆绑为JAR的Spring Boot应用程序中调用Python脚本。我为 Jython Standalone 2.7.1添加了Maven依赖性。以下代码在 execfile 调用时引发错误(该代码能够正确获取Python文件作为输入流):
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
String[] result = new String[2];
Properties preprops = System.getProperties();
Properties props = new Properties();
//props.put("python.home", "c:/Python27");
//props.put("python.path", "c:/Python27/Lib");
props.put("python.console.encoding", "UTF-8");
props.put("python.security.respectJavaAccessibility", "false");
props.put("python.import.site", "false");
PythonInterpreter.initialize(preprops, props, new String[0]);
PythonInterpreter pyInterpreter = new PythonInterpreter();
try {
Resource resource = new ClassPathResource("myPythonFile.py");
pyInterpreter.set("args", "a string argument");
pyInterpreter.setOut(out);
pyInterpreter.setErr(err);
pyInterpreter.execfile(resource.getInputStream());
result[0] = out.toString(); // reading the output
result[1] = err.toString(); // reading the error
} catch (Exception e) {
logger.error("Error in code: ", e);
} finally {
try {
if (out != null)
out.close();
if (err != null)
err.close();
pyInterpreter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
引发错误:
org.python.core.PyException: null
at org.python.core.Py.ImportError(Py.java:334) ~[jython-standalone-2.7.1.jar!/:na]
at org.python.core.imp.import_first(imp.java:879) ~[jython-standalone-2.7.1.jar!/:na]
at org.python.core.imp.import_module_level(imp.java:964) ~[jython-standalone-2.7.1.jar!/:na]
at org.python.core.imp.importName(imp.java:1057) ~[jython-standalone-2.7.1.jar!/:na]
at org.python.core.ImportFunction.__call__(__builtin__.java:1280) ~[jython-standalone-2.7.1.jar!/:na]
at org.python.core.PyObject.__call__(PyObject.java:450) ~[jython-standalone-2.7.1.jar!/:na]
at org.python.core.__builtin__.__import__(__builtin__.java:1232) ~[jython-standalone-2.7.1.jar!/:na]
at org.python.core.imp.importOne(imp.java:1076) ~[jython-standalone-2.7.1.jar!/:na]
at org.python.pycode._pyx1.f$0(<iostream>:251) ~[na:na]
at org.python.pycode._pyx1.call_function(<iostream>) ~[na:na]
at org.python.core.PyTableCode.call(PyTableCode.java:171) ~[jython-standalone-2.7.1.jar!/:na]
at org.python.core.PyCode.call(PyCode.java:18) ~[jython-standalone-2.7.1.jar!/:na]
at org.python.core.Py.runCode(Py.java:1614) ~[jython-standalone-2.7.1.jar!/:na]
at org.python.util.PythonInterpreter.execfile(PythonInterpreter.java:296) ~[jython-standalone-2.7.1.jar!/:na]
at org.python.util.PythonInterpreter.execfile(PythonInterpreter.java:291) ~[jython-standalone-2.7.1.jar!/:na]
我的Python脚本使用以下导入:
import sys
import argparse
import re
import json
我认为可能是因为我无法设置属性“ python.home ”或“ python.path ”,但我不确定如何设置我能做到这一点吗(Spring Boot将Jython JAR捆绑在 BOOT-INF / lib 下)。如果将“ python.home ”或“ python.path ”属性设置为本地Python安装路径,则代码可以正常工作。
感谢您为解决此问题所提供的帮助。 https://github.com/dchucks/jython上有一个示例应用程序可帮助重现该错误。