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

发布于 2024-08-29 03:49:37 字数 865 浏览 5 评论 0原文

我正在尝试使用 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

I'm trying to call Jython from a Java 6 application using javax.script:

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();
        }       
    }
}

This is causing a NullPointerException:

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

Does anyone have any idea what I'm doing wrong here?

Edit:

Thanks for the responses! I added jython.jar to the classpath and it runs properly:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悸初 2024-09-05 03:49:37

您必须先注册您的引擎。

来自: ScriptEngineManager .getEngineByName

[...]首先搜索已注册为句柄的 ScriptEngineFactory [...]如果未找到此类工厂,则返回 null

用户指南显示 要将其与 JSR-223 一起使用,您必须:

从 Jython 2.5.1 开始,JSR 223 的实现捆绑在 jython.jar 中。只需将 jython 添加到您的 CLASSPATH 并请求 python 脚本引擎即可。

您已经这样做了吗?

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

You have to register your engine first.

From: ScriptEngineManager.getEngineByName:

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

The user guide says to use it with JSR-223 you have to:

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.

Did you do that already?

EDIT
About your comment: I think you should open a new question, you'll get better answers.

歌枕肩 2024-09-05 03:49:37

您可能必须为“python”注册一个 ScriptEngineFactory

You'd probably have to register a ScriptEngineFactory for'python'

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文