I wonder if it is possible to use GraalPython as a Java library to interpret Python code on a standard JVM. If so, would it be a good choice to replace Jython (which only supports Python 2.7)?
Is this possible without importing the entire GraalVM project? I expect only Truffle and the Python interpreter built on top of it should be necessary.
If this is not possible, are there any good Java implementations of Python 3 available?
Update: starting from version 23.1, all GraalVM additional languages can now be easily embedded in Java, including non-Graal JDKs (but with caveats!) by using Maven artifacts published on Mavencentral. Those artifacts embed and on-demand extract the necessary files.
So using GraalPy in Java is as simple as adding this to pom.xml
(or equivalent code for the build system of your choice):
<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>
then one can run Python code via GraalPy just like so:
try (var ctx = org.graalvm.polyglot.Context.create()) {
ctx.eval("python", "print('Hello world')");
}
The caveat for non-GraalVM JDKs is that they do not support JIT compilation of Python code. You will get a warning like this:
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.
Old answer applicable to GraalVM/GraalPy version < 21.3.0
You should be able to run any GraalVM language on any JDK as their are just Java programs. However, the performance will be affected a lot. Moreover, languages like python consist of additional resources (standard library files, etc.) that you would have pull from GraalVM too.
This document about GraalVM JavaScript discusses this in more detail and describes how to run GraalVM JavaScript on stock JDK without compromising the performance. Some of it can be applicable to GraalPython.
https://github.com/graalvm/graaljs/blob/master/docs/user/RunOnJDK.md
Tl;dr: it will be much easier to use GraalVM. It's full JDK distribution. You are not missing on anything. If you can't, there are some ways.
Disclaimer: I am one of GraalPy developers.