Convert Figma logo to code with AI

ninia logojep

Embed Python in Java

1,377
152
1,377
74

Top Related Projects

GraalPy – A high-performance embeddable Python 3 runtime for Java

1,347

Python for the Java Platform

1,165

JPype is cross language bridge to allow Python programs full access to Java class libraries.

1,421

Access Java classes from Python

Quick Overview

Jep (Java Embedded Python) is a library that allows Python code to be embedded in Java applications. It provides seamless integration between Java and Python, enabling developers to leverage Python's extensive libraries and flexibility within Java projects.

Pros

  • Seamless integration between Java and Python
  • Access to Python's rich ecosystem of libraries from Java
  • High performance due to direct JNI calls
  • Support for multithreading and concurrent Python interpreters

Cons

  • Requires native libraries, which can complicate deployment
  • Limited support for some advanced Python features
  • Potential for memory leaks if not managed properly
  • Learning curve for developers unfamiliar with JNI or Python embedding

Code Examples

  1. Creating a Python interpreter and executing a simple statement:
try (Interpreter interp = new SharedInterpreter()) {
    interp.exec("print('Hello from Python!')");
}
  1. Calling a Python function from Java:
try (Interpreter interp = new SharedInterpreter()) {
    interp.exec("def greet(name):\n    return f'Hello, {name}!'");
    PyObject greetFunc = interp.getValue("greet");
    String result = greetFunc.call("Alice").toString();
    System.out.println(result);  // Outputs: Hello, Alice!
}
  1. Passing Java objects to Python:
try (Interpreter interp = new SharedInterpreter()) {
    interp.set("javaList", Arrays.asList(1, 2, 3, 4, 5));
    interp.exec("print(sum(javaList))");  // Outputs: 15
}

Getting Started

To use Jep in your Java project:

  1. Add Jep dependency to your project (e.g., using Maven):
<dependency>
    <groupId>black.ninia</groupId>
    <artifactId>jep</artifactId>
    <version>4.1.1</version>
</dependency>
  1. Ensure Python is installed on your system and JAVA_HOME is set.

  2. Set the java.library.path to include the directory containing the Jep native library.

  3. Use Jep in your Java code:

import jep.Interpreter;
import jep.SharedInterpreter;

public class JepExample {
    public static void main(String[] args) {
        try (Interpreter interp = new SharedInterpreter()) {
            interp.exec("print('Jep is working!')");
        }
    }
}

Competitor Comparisons

GraalPy – A high-performance embeddable Python 3 runtime for Java

Pros of GraalPython

  • High-performance Python implementation with JIT compilation
  • Seamless Java interoperability through Truffle framework
  • Supports Python 3.8+ features and standard library

Cons of GraalPython

  • Larger footprint and longer startup time
  • Less mature and potentially less stable than CPython
  • Limited support for some Python C extensions

Code Comparison

GraalPython:

import java
from java.lang import System

System.out.println("Hello from GraalPython!")

Jep:

from jep import Jep

with Jep() as jep:
    jep.eval('System.out.println("Hello from Jep!");')

Key Differences

  • GraalPython aims for full Python language compatibility, while Jep focuses on Python-Java integration
  • GraalPython is part of the GraalVM ecosystem, whereas Jep is a standalone project
  • Jep uses CPython and allows embedding Python in Java applications, while GraalPython is a separate Python implementation

Use Cases

  • GraalPython: High-performance Python applications, polyglot environments
  • Jep: Embedding Python in existing Java applications, tighter Java-Python integration

Community and Support

  • GraalPython: Backed by Oracle, active development, growing community
  • Jep: Smaller but dedicated community, longer project history
1,347

Python for the Java Platform

Pros of Jython

  • Full Python implementation in Java, allowing seamless integration with Java libraries
  • Supports most Python standard library modules
  • Can compile Python code to Java bytecode for improved performance

Cons of Jython

  • Slower development cycle compared to CPython
  • Limited support for C extension modules
  • Not fully compatible with the latest Python versions

Code Comparison

Jython:

from javax.swing import JFrame, JLabel

frame = JFrame("Hello, Jython!")
label = JLabel("Welcome to Jython")
frame.add(label)
frame.setSize(300, 100)
frame.setVisible(True)

Jep:

import jep
from java.awt import Frame

jep.shared.create_java_instance("java.awt.Frame", "Hello, Jep!")
frame = jep.shared.get_java_instance("frame")
frame.setSize(300, 100)
frame.setVisible(True)

Both Jython and Jep aim to bridge Python and Java, but they take different approaches. Jython provides a complete Python implementation in Java, offering broader compatibility with Python libraries. Jep, on the other hand, focuses on embedding CPython in Java applications, which can be more suitable for specific use cases where tighter integration with existing Java code is required.

1,165

JPype is cross language bridge to allow Python programs full access to Java class libraries.

Pros of JPype

  • More mature project with longer development history
  • Supports a wider range of Java versions
  • Better integration with Java threading and synchronization

Cons of JPype

  • Slower startup time compared to Jep
  • More complex setup process
  • Less actively maintained in recent years

Code Comparison

JPype example:

import jpype
jpype.startJVM()
java.lang.System.out.println("Hello, World!")
jpype.shutdownJVM()

Jep example:

import jep
jep.init_jvm()
jep.eval('System.out.println("Hello, World!");')

Both Jep and JPype are libraries for integrating Java and Python, allowing Python code to call Java methods and classes. JPype provides a more comprehensive Java integration but may be slower to start up, while Jep offers a simpler interface and faster startup times. JPype supports a wider range of Java versions and has better threading support, but Jep is more actively maintained and has a simpler setup process. The choice between the two depends on specific project requirements, such as performance needs, Java version compatibility, and the complexity of Java integration required.

1,421

Access Java classes from Python

Pros of Pyjnius

  • More actively maintained with recent updates
  • Broader platform support, including Android
  • Simpler setup process for many use cases

Cons of Pyjnius

  • Less flexible in handling complex Java types
  • May have performance overhead in certain scenarios
  • Limited support for advanced Java features like anonymous classes

Code Comparison

Pyjnius:

from jnius import autoclass
String = autoclass('java.lang.String')
s = String("Hello World")
print(s.toLowerCase())

Jep:

import jep
jep.shared.jep_java_import('java.lang.String')
s = String("Hello World")
print(s.toLowerCase())

Both libraries aim to provide Python-Java interoperability, but they differ in implementation and focus. Pyjnius is part of the Kivy project and is designed with mobile development in mind, while Jep is more focused on embedding Python in Java applications. Pyjnius generally offers an easier setup process and broader platform support, making it a good choice for many Python developers looking to use Java libraries. However, Jep may provide better performance and more advanced Java integration in certain scenarios, particularly when working with complex Java types or when embedding Python in Java applications.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

.. image:: https://img.shields.io/pypi/pyversions/Jep.svg :target: https://pypi.python.org/pypi/jep

.. image:: https://img.shields.io/pypi/l/Jep.svg :target: https://pypi.python.org/pypi/jep

.. image:: https://img.shields.io/pypi/v/Jep.svg :target: https://pypi.python.org/pypi/jep

.. image:: https://img.shields.io/badge/docs-wiki-orange.svg :target: https://github.com/ninia/jep/wiki

.. image:: https://img.shields.io/badge/docs-javadoc-orange.svg :target: https://ninia.github.io/jep/javadoc

Jep - Java Embedded Python

Jep embeds CPython in Java through JNI.

Some benefits of embedding CPython in a JVM:

  • Using the native Python interpreter may be much faster than alternatives.

  • Python is mature, well supported, and well documented.

  • Access to high quality Python modules, both native CPython extensions and Python-based.

  • Compilers and assorted Python tools are as mature as the language.

  • Python is an interpreted language, enabling scripting of established Java code without requiring recompilation.

  • Both Java and Python are cross platform, enabling deployment to different operating systems.

Installation

Simply run pip install --no-cache-dir --no-build-isolation jep or download the source and run pip install .. Building and installing require the JDK, Python, setuptools, and optionally numpy to be installed beforehand. The --no-cache-dir and --no-build-isolation options are not strictly required, however those settings enable Jep to make customizations for your environment such as enabling numpy specific behavior if numpy is installed.

Dependencies

  • Python >= 3.6
  • Java >= 1.8
  • NumPy >= 1.7 (optional)

Notable features

  • Interactive Jep console much like Python's interactive console
  • Supports multiple, simultaneous, mostly sandboxed sub-interpreters or shared interpreters
  • Numpy support for Java primitive arrays

Help

  • Documentation <https://github.com/ninia/jep/wiki>_
  • JavaDoc <https://ninia.github.io/jep/javadoc>_
  • Mailing List (deprecated) <https://groups.google.com/d/forum/jep-project>_
  • Known Issues and Help <https://github.com/ninia/jep/issues>_
  • Contribution Guidelines <https://github.com/ninia/jep/blob/master/.github/CONTRIBUTING.md>_
  • Project Page <https://github.com/ninia/jep>_

We welcome comments, contributions, bug reports, wiki documentation, etc.

If you need help, please first search for existing solutions online, in the the issues, and on the wiki. If you still need help, please open a GitHub issue and we will try and help you. Please remember to close the issue once it has been resolved.

Jep Team