Package jep

Interface Interpreter

  • All Superinterfaces:
    java.lang.AutoCloseable
    All Known Implementing Classes:
    Jep, SharedInterpreter, SubInterpreter

    public interface Interpreter
    extends java.lang.AutoCloseable
    An interface for using a Python Interpreter.

    Embeds CPython in Java. Each Interpreter instance provides access to a Python interpreter and maintains an independent global namespace for Python variables. Values can be passed from Java to Python using the set(String, Object) method. Various methods, such as exec(String) and invoke(String, Object...) can be used to execute Python code. Python variables can be accessed using getValue(String) and getValue(String, Class).

    Methods called on an Interpreter must be called from the same thread that created the instance. To maintain stability, avoid having two Interpreter instances running on the same thread at the same time. Instead provide different threads or close() one before instantiating another on the same thread. Interpreter instances should always be closed when no longer needed to prevent memory leaks.

    Since:
    3.9
    • Method Summary

      All Methods Instance Methods Abstract Methods 
      Modifier and Type Method Description
      void close()  
      boolean eval​(java.lang.String str)
      Evaluate Python statements.
      void exec​(java.lang.String str)
      Execute an arbitrary number of Python statements in this interpreter.
      java.lang.Object getValue​(java.lang.String str)
      Retrieves a value from this Python interpreter.
      <T> T getValue​(java.lang.String str, java.lang.Class<T> clazz)
      Like getValue(String) but allows specifying the return type.
      java.lang.Object invoke​(java.lang.String name, java.lang.Object... args)
      Invokes a Python function.
      java.lang.Object invoke​(java.lang.String name, java.lang.Object[] args, java.util.Map<java.lang.String,​java.lang.Object> kwargs)
      Invokes a Python function.
      java.lang.Object invoke​(java.lang.String name, java.util.Map<java.lang.String,​java.lang.Object> kwargs)
      Invokes a Python function.
      void runScript​(java.lang.String script)
      Runs a Python script.
      void set​(java.lang.String name, java.lang.Object v)
      Sets the Java Object into the interpreter's global scope with the specified variable name.
    • Method Detail

      • invoke

        java.lang.Object invoke​(java.lang.String name,
                                java.lang.Object... args)
                         throws JepException
        Invokes a Python function.
        Parameters:
        name - a Python function name in globals dict or the name of a global object and method using dot notation
        args - args to pass to the function in order
        Returns:
        an Object value
        Throws:
        JepException - if an error occurs
      • invoke

        java.lang.Object invoke​(java.lang.String name,
                                java.util.Map<java.lang.String,​java.lang.Object> kwargs)
                         throws JepException
        Invokes a Python function.
        Parameters:
        name - a Python function name in globals dict or the name of a global object and method using dot notation
        kwargs - a Map of keyword args
        Returns:
        an Object value
        Throws:
        JepException - if an error occurs
      • invoke

        java.lang.Object invoke​(java.lang.String name,
                                java.lang.Object[] args,
                                java.util.Map<java.lang.String,​java.lang.Object> kwargs)
                         throws JepException
        Invokes a Python function.
        Parameters:
        name - a Python function name in globals dict or the name of a global object and method using dot notation
        args - args to pass to the function in order
        kwargs - a Map of keyword args
        Returns:
        an Object value
        Throws:
        JepException - if an error occurs
      • eval

        boolean eval​(java.lang.String str)
              throws JepException

        Evaluate Python statements.

        In interactive mode, Jep may not immediately execute the given lines of code. In that case, eval() returns false and the statement is stored and is appended to the next incoming string.

        If you're running an unknown number of statements, finish with eval(null) to flush the statement buffer.

        Interactive mode is slower than a straight eval call since it has to compile the code strings to detect the end of the block. Non-interactive mode is faster, but code blocks must be complete. For example:

         interactive mode == false
         jep.eval("if(Test):\n    print('Hello world')");
         
         interactive mode == true
         jep.eval("if(Test):");
         jep.eval("    print('Hello world')");
         jep.eval(null);
         
         

        Also, Python does not readily return object values from eval(). Use getValue(String) instead.

        Note: Interactive mode will be removed in a future release. This method may still be used for executing individual statements. See console.py for an example of how to interactively execute Python using the builtin compile() and exec() functions.

        Parameters:
        str - a String statement to eval
        Returns:
        true if statement complete and was executed.
        Throws:
        JepException - if an error occurs
      • exec

        void exec​(java.lang.String str)
           throws JepException
        Execute an arbitrary number of Python statements in this interpreter. Similar to the Python builtin exec function.
        Parameters:
        str - Python code to exececute
        Throws:
        JepException - if an error occurs
      • runScript

        void runScript​(java.lang.String script)
                throws JepException
        Runs a Python script.
        Parameters:
        script - a String absolute path to script file.
        Throws:
        JepException - if an error occurs
      • getValue

        java.lang.Object getValue​(java.lang.String str)
                           throws JepException

        Retrieves a value from this Python interpreter. Supports retrieving:

        • Java objects
        • Python None (null)
        • Python strings
        • Python True and False
        • Python numbers
        • Python lists
        • Python tuples
        • Python dictionaries

        For Python containers, such as lists and dictionaries, getValue will recursively move through the container and convert each item. If the type of the value retrieved is not supported, Jep will fall back to returning a String representation of the object. This fallback behavior will probably change in the future and should not be relied upon.

        Parameters:
        str - the name of the Python variable to get from the interpreter's global scope
        Returns:
        an Object value
        Throws:
        JepException - if an error occurs
      • getValue

        <T> T getValue​(java.lang.String str,
                       java.lang.Class<T> clazz)
                throws JepException
        Like getValue(String) but allows specifying the return type. If Jep cannot convert the variable to the specified type then a JepException is thrown. This can be used to safely ensure that the return value is an expected type. The following table describes what conversions are currently possible.
        The valid classes for Python to Java conversions
        Python Class Java Classes Notes
        str/unicode String, Character Character conversion will fail if the str is longer than 1.
        bool Boolean
        int/long Long, Integer, Short, Byte Conversion fails if the number is outside the valid range for the Java type
        float Double, Float
        list, tuple List, array When a tuple is converted to a List it is unmodifiable.
        dict Map
        function, method Any FunctionalInterface
        Buffer Protocol array This includes Python classes such as bytes, bytearray and array.array
        numpy.ndarray NDArray Only if Jep was built with numpy support
        numpy.float64 Double, Float
        numpy.float32 Float, Double
        numpy.int64 Long, Integer, Short, Byte Conversion fails if the number is outside the valid range for the Java type
        numpy.int32 Integer, Long, Short, Byte Conversion fails if the number is outside the valid range for the Java type
        numpy.int16 Short, Integer, Long, Byte Conversion fails if the number is outside the valid range for the Java type
        numpy.int8 Byte. Short, Integer, Long
        NoneType Any(null)
        Jep objects such as PyJObjects and jarrays will be returned if the Java type of the wrapped object is compatible.
        Anything else String, PyObject String conversion will likely be removed in future versions of Jep so it is unsafe to depend on this behavior.
        Type Parameters:
        T - the generic type of the return type
        Parameters:
        str - the name of the Python variable to get from the interpreter's global scope
        clazz - the Java class of the return type.
        Returns:
        a Java version of the variable
        Throws:
        JepException - if an error occurs
      • set

        void set​(java.lang.String name,
                 java.lang.Object v)
          throws JepException
        Sets the Java Object into the interpreter's global scope with the specified variable name.
        Parameters:
        name - the Python name for the variable
        v - an Object value
        Throws:
        JepException - if an error occurs
      • close

        void close()
            throws JepException
        Specified by:
        close in interface java.lang.AutoCloseable
        Throws:
        JepException