不积跬步,无以至千里;不积小流,无以成江海。

java环境运行python脚本:Cannot invoke "javax.script.ScriptEngine.getFactory()" because "scriptEngine" is null

JAVA 康康 1471℃ 0评论

在用Liteflow规则引擎中,用到了python脚本,发现ide启动时脚本正常运行,到了线上环境就报异常。经过调试发现 scriptEngineManager.getEngineByName("python");获取到的engine为null。

public ScriptExecutor init() throws ScriptException {
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
scriptEngine = scriptEngineManager.getEngineByName(scriptEngineName());
if (scriptEngine == null) {
log.error("load scriptEngine[{}] error: scriptEngine is null!", scriptEngineName());
throw new ScriptException("load scriptEngine[" + scriptEngineName() + "] error, scriptEngine is null !");
}
return this;
}

正好刚注册了个GhatGpt,于是直接来问一下:

根据ChatGpt提示尝试新增python.home,指定 jython-standalone-2.7.3.jar的绝对路径可以解决。

由于应用打好Jar包里面已经有了jython-standalone依赖,不想再在部署的时候额外拿个jar包进去,所以又做了点改动:应用启动时,判断当jar包运行时,从BOOT-INF/lib下将jython拷贝出来,并设置python.home:

@Slf4j
@Component
public class ApplicationInitRunner implements CommandLineRunner {

    @Value("${python.home:}")
    private String pythonHome;

    @Override
    public void run(String... args)  {
        if (StringUtils.isNotBlank(pythonHome)) {
            //复制jython包到python home
            boolean copyed = JarExtractor.copyJython2PythonHome(pythonHome);
            if(copyed){
                System.setProperty("python.import.site","false");
                System.setProperty("python.home",pythonHome);
            }
        }
    }

}

以下拷贝jar包代码片段:

final static String jythonName = "jython-standalone-2.7.3.jar";

/**
* 判断是否从jar包运行
* @return
*/
public static boolean isRunningFromJar() {
URL resource = JarExtractor.class.getResource("");
return resource != null && resource.getProtocol().equals("jar");
}

public static boolean copyJython2PythonHome(String pythonHome){
return copyJar(jythonName,pythonHome);
}

/**
* 拷贝包里的依赖到指定目录
* @param jarName
* @param targetPath
*/
public static boolean copyJar(String jarName,String targetPath){
if(isRunningFromJar()){
ClassLoader defaultClassLoader = ClassUtils.getDefaultClassLoader();
try (InputStream inputStream = defaultClassLoader.getResourceAsStream("BOOT-INF/lib/"+jarName)) {
if(inputStream != null){
log.info("CopyJar:{} -> {}",jarName,targetPath);
write2File(inputStream,targetPath);
return true;
}
} catch (Exception e) {
log.error("jar {} -> {} copy error: {}",jarName,e.getMessage());
}
}
return false;
}

转载请注明:左手代码右手诗 » java环境运行python脚本:Cannot invoke "javax.script.ScriptEngine.getFactory()" because "scriptEngine" is null

喜欢 (1)or分享 (0)
发表我的评论
取消评论

 

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址