通过脚本引擎(jython)从Java调用Python? [英] Calling Python from Java through scripting engine (jython)?
问题描述
我正在尝试使用 javax.script
从Java 6应用程序调用Jython:
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();
}
}
}
这导致NullPointerException:
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?
编辑:
感谢您的回复!我将jython.jar添加到类路径中并且运行正常:
Thanks for the responses! I added jython.jar to the classpath and it runs properly:
java -cp "./;jython.jar" jythonEx
推荐答案
您必须先注册您的引擎。
You have to register your engine first.
来自: ScriptEngineManager.getEngineByName :
[.. 。]首先搜索已注册为句柄的ScriptEngineFactory [...]如果没有找到这样的工厂,则返回null
用户指南说与JSR-223一起使用你必须:
从Jython 2.5.1开始,JSR 223的实现被捆绑在jython.jar中。只需将jython添加到您的CLASSPATH并请求python脚本引擎。
您是否已经这样做了?
编辑
关于你的评论:我认为你应该开一个新问题,你会得到更好的答案。
EDIT About your comment: I think you should open a new question, you'll get better answers.
这篇关于通过脚本引擎(jython)从Java调用Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!