通过脚本引擎(jython)从Java调用Python?

2024-05-19 01:14:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用javax.script从Java6应用程序调用Jython:

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class jythonEx
{
    public static void main (String args[]) throws ScriptException
    {
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine pyEngine = mgr.getEngineByName("python");
        try {
            pyEngine.eval("print \"Python - Hello, world!\"");
        } catch (Exception ex) {
            ex.printStackTrace();
        }       
    }
}

这导致了NullPointerException:

java.lang.NullPointerException
        at jythonEx.main(jythonEx.java:12)

有人知道我做错了什么吗?

编辑:

谢谢你的回复!我将jython.jar添加到类路径中,它运行正常:

java -cp "./;jython.jar" jythonEx

Tags: importmainscriptjythonjavapublicexmgr
2条回答

你必须先注册你的引擎。

发件人:ScriptEngineManager.getEngineByName

[...] first searches for a ScriptEngineFactory that has been registered as a handle [...] Returns null if no such factory was found

用户指南上说to use it with JSR-223您必须:

As of Jython 2.5.1 an implementation of JSR 223 is bundled in jython.jar. Simply add jython to your CLASSPATH and ask for the python script engine.

你已经这么做了吗?

编辑 关于你的评论:我认为你应该提出一个新问题,你会得到更好的答案。

您可能需要为“python”注册一个ScriptEngineFactory

相关问题 更多 >

    热门问题