oracle / graalpython

GraalPy – A high-performance embeddable Python 3 runtime for Java
https://www.graalvm.org/python/
Other
1.24k stars 108 forks source link

Embedding Virtualenv library #200

Closed SCadilhac closed 3 years ago

SCadilhac commented 3 years ago

Hi Team,

From Java code, is it possible to start Polyglot Python code evaluation in the context of a specific virtualenv (created with graalpython -m venv ...) to make use of the installed libraries?

Thanks for your help.

timfel commented 3 years ago

Hi, thanks for the question.

You need to set the context option python.Executable to the graalpython executable path inside your virtualenv folder (path/to/venv/bin/graalpython). The executable path is used by the Python site module to determine where to search for packages

SCadilhac commented 3 years ago

Hi @timfel,

Thanks for the quick reply! I cannot make it work though, any idea of what I might be missing? In the test below, I import a library from the GraalPython shell successfully, but can't import the same library from the Polyglot context.

23:23 user@dev01 ~% source testenv/bin/activate
(testenv) 23:24 user@dev01 ~% python
Python 3.8.5 (Fri Jan 15 18:52:18 UTC 2021)
[Graal, GraalVM CE, Java 11.0.10] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ciscoconfparse
>>>
>>>
(testenv) 23:24 user@dev01 ~% cat Test.java
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Engine;
import org.graalvm.polyglot.PolyglotException;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.Value;

class Test {

    final static private String script = "" +
        "import ciscoconfparse\n" +
        "";

    public static void main(String[] args) {
        Context context = Context.newBuilder()
            .allowIO(true).allowAllAccess(true)
            .allowExperimentalOptions(true)
            .option("python.Executable", "/home/user/testenv/bin/graalpython")
            .build();
        context.initialize("python");
        context.enter();
        context.eval("python", script);
    }
}
(testenv) 23:24 user@dev01 ~% javac Test.java
(testenv) 23:24 user@dev01 ~% java Test
Exception in thread "main" ModuleNotFoundError: No module named 'ciscoconfparse'
    at org.graalvm.sdk/org.graalvm.polyglot.Context.eval(Context.java:373)
    at Test.main(Test.java:21)
(testenv) 23:25 user@dev01 ~% java -version
openjdk version "11.0.10" 2021-01-19
OpenJDK Runtime Environment GraalVM CE 21.0.0 (build 11.0.10+8-jvmci-21.0-b06)
OpenJDK 64-Bit Server VM GraalVM CE 21.0.0 (build 11.0.10+8-jvmci-21.0-b06, mixed mode, sharing)
timfel commented 3 years ago

You first need to run import site. This module is automatically imported by the launcher and is responsible for setting up the import paths

SCadilhac commented 3 years ago

Thanks!