Jython由"getEngineFactories"列出,而"getEngineByName("jython"))则为"null". [英] Jython listed by `getEngineFactories`, but `getEngineByName("jython")` is `null`
问题描述
我创建了一个默认的Maven Java项目并添加了以下依赖项:
I created a default Maven Java project and added the following dependency:
<dependency>
<groupId>org.python</groupId>
<artifactId>jython</artifactId>
<version>2.7.0</version>
</dependency>
然后我创建了一个包 src/main/java/mypkg
并添加了此类:
Then I created a package src/main/java/mypkg
and added this class:
package mypkg;
import javax.script.*;
class JythonMinimalTest {
public static void main(String[] args) throws Exception {
String engineName = "python";
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName(engineName);
if (engine == null) {
System.err.println("ERROR: `" + engineName + "` not available.");
System.err.println("Available engines: ");
for (ScriptEngineFactory factory: manager.getEngineFactories()) {
System.err.println(factory);
System.err.println("names:");
for (String name: factory.getNames()) {
System.err.println(" " + name);
}
}
System.exit(999);
}
engine.eval("print('hello, world')");
}
}
当我使用 exec:java
运行它时,
mvn exec:java -Dexec.mainClass=mypkg.JythonMinimalTest
我得到以下神秘输出:
ERROR: `python` not available.
Available engines:
org.python.jsr223.PyScriptEngineFactory@2b0e6c89
names:
python
jython
jdk.nashorn.api.scripting.NashornScriptEngineFactory@46618cb8
names:
nashorn
Nashorn
js
JS
JavaScript
javascript
ECMAScript
ecmascript
管理器返回 null
,但随后在下一行中列出可用脚本引擎中的 python
/ jython
.
The manager returns null
, but then in the next line lists python
/jython
among the available script engines.
Nashorn以完全相同的方式工作得很好.我的Jython怎么了?
Nashorn worked just fine in exactly the same way. What am I doing wrong with Jython?
推荐答案
这是一种解决方法:
将此添加到顶部:
import org.python.core.Options;
在调用 getEngineByName
之前,先设置
Options.importSite = false;
然后创建引擎,没有问题.
Then the engine is created without problems.
从另一个有效的解决方案(在注释中由mzjn提出)是将 jython
工件替换为 jython-standalone
.
Another solution that works well (proposed by mzjn in the comments) is to replace the jython
artifact by jython-standalone
.
这篇关于Jython由"getEngineFactories"列出,而"getEngineByName("jython"))则为"null".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!