Skip to content

Commit 6c9afff

Browse files
committed
document how to include venvs in java projects
1 parent 047be79 commit 6c9afff

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

docs/user/Packages.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,47 @@ Note that to try extensions on GraalVM's Python runtime, you have to download, b
4343
### Using `pip`
4444

4545
The `pip` package installer is available and working when using a `venv`.
46+
47+
### Including packages in a Java application
48+
49+
When using Python from Java via the GraalVM embedder APIs, a bit of preparationis required to make packages available to the runtime.
50+
After a venv is created and any desired packages are installed, this venv is made available to the Java embedded Python by setting a context option.
51+
A good idea is to include the entire venv folder as a resource, and use Java's resource API:
52+
53+
```java
54+
String venvExePath = getClass().
55+
getClassLoader().
56+
getResource(Paths.get("venv", "bin", "graalpython").toString()).
57+
getPath();
58+
59+
Context ctx = Context.newBuilder("python").
60+
allowIO(true).
61+
option("python.Executable", venvExePath).
62+
build();
63+
64+
ctx.eval("python", "import site");
65+
```
66+
67+
The initial `import site` loads the Python standard library module `site`, which sets up the library paths.
68+
To do so, it uses the path of the currently running Python executable.
69+
For a language like Python, which is built around the filesystem, this makes sense, but in our Java embedding context, we do not have a Python executable running.
70+
This is what the `python.Executable` option is for: it reports which executable _would be_ running if we were running Python directly inside our venv.
71+
That is enough to make the machinery work and any packages inside the venv available to the embedded Python in Java.
72+
73+
A simple venv is already quite heavy, because it comes with the machinery to install more packages.
74+
For a Java distribution, we can strip the venv down somewhat without much trouble.
75+
Just run these inside the top-level venv directory:
76+
```shell
77+
find . -type d -name "__pycache__" -exec rm -rf "{}" ";"
78+
rmdir include
79+
rm bin/*
80+
rmdir bin
81+
rm lib/python3.*/site-packages/easy_install.py
82+
rm -rf lib/python3.*/site-packages/pip*
83+
```
84+
85+
Some packages may require the following, but most do not, so you can also remove these, but be aware that it _may_ break a few packages:
86+
```shell
87+
rm -rf lib/python3.*/site-packages/setuptools*
88+
rm -rf lib/python3.*/site-packages/pkg_resources*
89+
```

0 commit comments

Comments
 (0)