Importing a local python file in an embedded graalpython script fails

226 views Asked by At

Is it possible to import a local python script in another script that is run from Java using graalpython?

On the Java (Scala) side, the code looks like this:

  val context =  Context.newBuilder("python").
    allowAllAccess(true).
    option("python.ForceImportSite", "true").
    option("python.Executable", "pyScripts/venv/bin/graalpython").
    build()
  val source = Source.newBuilder("python", new File("pyScripts/common/MyPyScript.py")).build()

  context.eval(source)
  val clazz = context.getPolyglotBindings.getMember("MyPyScript")
  val instance = clazz.newInstance()
  val res = instance.as(classOf[PyScriptApi])

Then in the graalpython script, I would like to do something like this (both python files are in the common subdirectory):

import java
import polyglot

from common.ScriptBase import ScriptBase

class MyPyScript(ScriptBase):
    ...

However that gives an error on the Scala side:

Exception in thread "main" ModuleNotFoundError: No module named 'common'

I know that the Scala code can evaluate this file, however I would like the script writer to be able to split the script into multiple files.

1

There are 1 answers

0
Allan On

It turns out that local imports work if you set the "python.PythonPath" option in the context in the Java/Scala code:

  val context =  Context.newBuilder("python")
    .allowAllAccess(true)
    .option("python.PythonPath", "pyScripts")
    .option("python.ForceImportSite", "true")
    .option("python.Executable", "pyScripts/venv/bin/graalpython")
    .build()