I am writing some java code that runs on graalvm
I want it to execute an python script
The python script use an 3rd party libray
When I run my java code it come out an ModuleNotFoundError Exception
// java code
public static void main(String[] args) throws IOException {
try(Context ctx = Context.newBuilder().allowAllAccess(true).build()){
Path scriptPath = Paths.get("/home/hyc/Desktop/py_script.py");
String script = Files.readString(scriptPath);
Value value = ctx.eval("python", script);
}
}
// py_script.py
import requests
url = 'http://www.google.com/'
strhtml = requests.get(url)
print(strhtml.text)
source code link: https://github.com/huangdaren1997/polyglotDemo
is graalvm guest languages can use 3rd party library ? And how to do it ?
OS: Manjaro 20.2 Nibia
Kernel: x86_64 Linux 5.9.11-3-MANJARO
Python: Python 3.8.6
openjdk 11 64-Bit Server VM GraalVM CE 20.3.0
First you need to install the package, which I assume you've done, but just to make this answer complete:
graalpython -m ginstall install requests
Then you need to configure GraalPython to import the site module. This is done by default if you run GraalPython via the executable, but not when you embed GraalPython in Java:
Context.newBuilder().option("python.ForceImportSite", "true")...
Note that this set-up will depend on the required packages being installed in the site library. Bit cleaner solution may be to use the venv
module that GraalPython also supports:
graalpython -m venv /path/to/you/new/venv/directory
then install what you need
/path/to/you/new/venv/directory/bin/graalpython -m ginstall install ...
and then additionally pass this option to GraalPython:
.option("python.SysPrefix", "/path/to/you/new/venv/directory")
Edit: there is now an article about this whole use-case: https://medium.com/graalvm/supercharge-your-java-apps-with-python-ec5d30634d18