You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中用ScriptEngine运行Python脚本失败:无法找到JythonScriptEngine

解决Jython ScriptEngine无法找到的问题

核心问题排查与修复步骤

1. 确认依赖包类型

必须使用jython-standalone-2.7.2.jar而非普通的jython.jar。普通jar包不包含ScriptEngine的注册类和服务配置文件,导致ScriptEngineManager无法识别Jython引擎。

  • 手动引入:直接下载standalone版本,添加到项目运行时类路径
  • Maven依赖配置:
<dependency>
    <groupId>org.python</groupId>
    <artifactId>jython-standalone</artifactId>
    <version>2.7.2</version>
</dependency>

2. 修正代码中的错误

你的代码存在两处关键问题:

  • 手动设置PySystemState会干扰ScriptEngineManager的自动环境初始化,需移除
  • 文件路径C:/*/MyScript.py是无效格式,*不能作为路径通配符,需替换为具体路径

修改后的代码:

import javax.script.*;
import java.io.FileReader;
import java.io.FileNotFoundException;

public class JythonRunner {
    public static void main(String[] args) throws FileNotFoundException, ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("python");

        // 增加引擎非空校验
        if (engine == null) {
            throw new RuntimeException("Jython ScriptEngine未找到,请确认jython-standalone已加入类路径");
        }

        StringWriter writer = new StringWriter();
        ScriptContext context = new SimpleScriptContext();
        context.setWriter(writer);

        // 替换为实际脚本路径
        engine.eval(new FileReader("C:/Users/User/MyScript.py"), context);
        System.out.println(engine.get("value"));
    }
}

3. 验证类路径配置

  • IDE环境:确保jython-standalone.jar被添加到运行时依赖(而非仅编译时),检查项目的运行配置中类路径是否包含该jar
  • 命令行运行:使用java -cp "jython-standalone-2.7.2.jar;你的项目类目录" JythonRunner,明确指定类路径

4. 兼容性检查

  • 若使用Java 11及以上版本,Jython 2.7.2可能存在兼容性问题,建议升级到Jython 2.7.3或更高测试版本
  • 检查jython-standalone.jar内是否存在META-INF/services/javax.script.ScriptEngineFactory文件,文件内需包含org.python.jsr223.PyScriptEngineFactory一行,缺失则说明jar包损坏,需重新下载

内容的提问来源于stack exchange,提问作者Skyliam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 14:51:25