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

前端之家收集整理的这篇文章主要介绍了通过脚本引擎(jython)从Java调用Python?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使用 javax.script从 Java 6应用程序调用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

解决方法

你必须先注册你的引擎.

从: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.

你有没有这样做?

编辑关于你的评论:我想你应该开一个新问题,你会得到更好的答案.

猜你在找的Java相关文章