使用 GraalPython 作为 Jython 替代品

问题描述 投票:0回答:1

我想知道是否可以使用 GraalPython 作为 Java 库来在标准 JVM 上解释 Python 代码。如果是这样,替换Jython(仅支持Python 2.7)会是一个不错的选择吗?

是否可以在不导入整个 GraalVM 项目的情况下实现这一点?我预计只有 Truffle 以及构建在其之上的 Python 解释器才是必要的。

如果这是不可能的,是否有可用的 Python 3 的良好 Java 实现?

java python jython graalvm
1个回答
2
投票

更新:从版本 23.1 开始,通过使用 Mavencentral 上发布的 Maven 工件,所有 GraalVM 附加语言现在都可以轻松嵌入到 Java 中,包括非 Graal JDK(但有警告!)。这些工件嵌入并按需提取必要的文件。

因此,在 Java 中使用 GraalPy 就像将其添加到

pom.xml
(或您选择的构建系统的等效代码)一样简单:

    <dependencies>
        <dependency>
            <groupId>org.graalvm.polyglot</groupId>
            <artifactId>polyglot</artifactId>
            <version>23.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.graalvm.polyglot</groupId>
            <artifactId>python-community</artifactId>
            <version>23.1.0</version>
            <type>pom</type>
        </dependency>
    </dependencies>

然后就可以通过 GraalPy 运行 Python 代码,就像这样:

try (var ctx = org.graalvm.polyglot.Context.create()) {
    ctx.eval("python", "print('Hello world')"); 
}

非 GraalVM JDK 的警告是它们不支持 Python 代码的 JIT 编译。您将收到如下警告:

The polyglot engine uses a fallback runtime that does not support runtime compilation to native code.
Execution without runtime compilation will negatively impact the guest application performance.
The following cause was found: JVMCI is not enabled for this JVM. Enable JVMCI using -XX:+EnableJVMCI.
For more information see: https://www.graalvm.org/latest/reference-manual/embed-languages/.
To disable this warning use the '--engine.WarnInterpreterOnly=false' option or the '-Dpolyglot.engine.WarnInterpreterOnly=false' system property.

适用于 GraalVM/GraalPy 版本的旧答案 < 21.3.0

您应该能够在任何 JDK 上运行任何 GraalVM 语言,因为它们只是 Java 程序。但是,性能会受到很大影响。此外,像 python 这样的语言包含额外的资源(标准库文件等),您也可以从 GraalVM 中获取这些资源。

这篇关于 GraalVM JavaScript 的文档对此进行了更详细的讨论,并描述了如何在普通 JDK 上运行 GraalVM JavaScript,而不影响性能。其中一些可以适用于 GraalPython。

https://github.com/graalvm/graaljs/blob/master/docs/user/RunOnJDK.md

Tl;dr:使用 GraalVM 会容易得多。它是完整的 JDK 发行版。你没有错过任何东西。如果你做不到,还有一些方法。

© www.soinside.com 2019 - 2024. All rights reserved.