Skip to content

Instantly share code, notes, and snippets.

@timfel
Last active May 5, 2023 12:08
Show Gist options
  • Save timfel/d5bc6d8aec7cab4587074e9549100231 to your computer and use it in GitHub Desktop.
Save timfel/d5bc6d8aec7cab4587074e9549100231 to your computer and use it in GitHub Desktop.
Supercharge Your Java Apps With Python Blogpost
Context context = Context.newBuilder("python").
allowAllAccess(true).
option("python.ForceImportSite", "true").
option("python.Executable", VENV_EXECUTABLE).
build();
interface GraphRenderer {
InputStream render(String function, int steps);
}
Main.class.getClassLoader().getResource("venv/bin/python").getPath();
<id>enforce-graalvm-python</id>
<phase>validate</phase>
<goals><goal>enforce</goal></goals>
<configuration>
<rules>
<requireFilesExist>
<message>JAVA_HOME must be a GraalVM with Python installed. Download GraalVM from https://www.graalvm.org/downloads and install the Python component: `gu install python`</message>
<files><file>${env.JAVA_HOME}/bin/graalpy</file></files>
</requireFilesExist>
</rules>
<fail>true</fail>
</configuration>
<executions>
<execution>
<id>Prepare venv</id>
<phase>generate-resources</phase>
<goals><goal>exec</goal></goals>
<configuration>
<executable>${env.JAVA_HOME}/bin/graalpy</executable>
<arguments>
<argument>-m</argument>
<argument>venv</argument>
<argument>venv</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>Install required packages into venv</id>
<phase>generate-resources</phase>
<goals><goal>exec</goal></goals>
<configuration>
<executable>venv/bin/pip</executable>
<arguments>
<argument>install</argument>
<argument>pygal==2.4.0</argument>
</arguments>
<environmentVariables>
<VIRTUAL_ENV>${project.basedir}/venv</VIRTUAL_ENV>
</environmentVariables>
</configuration>
</execution>
</executions>
<resource>
<directory>${project.basedir}</directory>
<includes>
<include>venv/**/*</include>
</includes>
</resource>
Value pygalRendererClass = context.getPolyglotBindings().getMember("PygalRenderer");
Value pygalRenderer = pygalRendererClass.newInstance();
pygalRenderer.as(GraphRenderer.class);
import polyglot
polyglot.export_value("PygalRenderer", PygalRenderer)
class PygalRenderer:
def render(self, func, steps):
values = []
x = -100
while x < 100:
values.append(eval(func, globals={"x": x, **math.__dict__}))
x += 200 / steps
chart = pygal.Line(fill=False)
chart.add(f"f(x) = {func}", values)
svg_data = chart.render()
stream = SVGInputStream()
stream.this.bytestream = iter(svg_data)
return stream
class SVGInputStream(java.io.InputStream):
def read(self, *args):
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment