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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2671768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:18:05  来源:igfitidea点击:

Calling Python from Java through scripting engine (jython)?

javapythonjythonjavax.script

提问by griffin

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

我正在尝试使用以下命令从 Java 6 应用程序调用 Jython 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:

这会导致 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:

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

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

回答by OscarRyz

You have to register your engine first.

您必须先注册您的引擎。

From: ScriptEngineManager.getEngineByName:

来自:ScriptEngineManager.getEngineByName

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

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

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

用户指南说要将它与 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.

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

Did you do that already?

你已经这样做了吗?

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

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

回答by Petre Maierean

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

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