Jython
Jython is an implementation of the Python programming language designed to run on the Java Virtual Machine (JVM), enabling seamless integration of Python code with Java libraries and applications.[1] Originally developed as JPython by Jim Hugunin in late 1997 while he was at the Corporation for National Research Initiatives (CNRI), it was renamed Jython in 1999 under the leadership of Barry Warsaw, who became the primary developer after Hugunin's departure.[2] The project moved to SourceForge in October 2000, with Finn Bock taking over as primary maintainer shortly thereafter.[3]
Jython's core strength lies in its ability to combine Python's concise syntax and rapid development capabilities—often resulting in code that is 2 to 10 times shorter than equivalent Java implementations—with Java's robust ecosystem, garbage collection, and platform independence.[4] It supports nearly all of the Python 2.7 standard library but does not accommodate CPython's C extension modules, relying instead on Java's bytecode and class libraries for performance and interoperability.[5] Key use cases include embedded scripting in Java-based systems, interactive experimentation with Java packages via its REPL, and accelerating development in environments like IBM WebSphere, Apache Pig, and ImageJ.[1]
As of November 2025, the stable release is Jython 2.7.4 (released August 18, 2024), closely aligned with CPython 2.7, with built-in support for tools like pip and setuptools but without C extensions.[6][7] Development of Jython 3.x, which would support modern Python 3 syntax and features, is ongoing via the project's GitHub repository, though it remains in an experimental snapshot stage.[1] Licensed under the Python Software Foundation License version 2, Jython is freely available for both commercial and non-commercial use, fostering its role as a bridge between the Python and Java communities.[1]
Introduction
Definition and purpose
Jython is an implementation of the Python programming language designed to run on the Java platform, specifically the Java Virtual Machine (JVM).[1][5] It allows developers to write Python code that compiles to Java bytecode, enabling seamless execution within Java environments. Originally known as JPython, it was renamed Jython in 1999 to better reflect its focus on the Java ecosystem.[5][8]
The primary purpose of Jython is to empower Python developers to harness the JVM's performance, extensive libraries, and deployment capabilities while retaining Python's syntax and productivity advantages.[1][8] This integration facilitates rapid application development, where Python scripts can be 2-10 times shorter than equivalent Java code, boosting efficiency in scripting and prototyping.[1]
Key benefits include bidirectional access to Java classes and libraries directly from Python code, eliminating the need for code rewrites or complex wrappers.[1][8] For instance, Python scripts can import and instantiate Java objects, such as those from java.lang or javax.swing, to leverage enterprise-grade tools for tasks like GUI development or database connectivity, while Java applications can embed Jython for dynamic scripting.[8] This bridging role makes Jython particularly valuable in mixed-language environments, combining Python's ease of use with Java's robustness.[1]
Relation to Python and Java
Jython serves as a compliant implementation of the Python programming language designed specifically for the Java Virtual Machine (JVM), adhering closely to the syntax and semantics of Python 2.7 as defined by CPython, the reference implementation written in C. Unlike CPython, which executes Python code through a C-based runtime environment, Jython is not a direct port but rather a reimplementation that parses Python abstract syntax trees (AST) and compiles them into JVM bytecode for execution. This approach ensures that Jython supports nearly all of the core Python standard library modules available in CPython 2.7, allowing developers familiar with Python to write code that behaves identically in most respects, though it diverges in areas like support for C extension modules (e.g., .so or .pyd files), which are incompatible due to the absence of a C runtime.[5][1]
A primary distinction between Jython and CPython lies in Jython's runtime environment, which leverages the JVM's bytecode execution model instead of CPython's interpreter loop and reference counting for memory management; Jython relies on Java's garbage collection, potentially affecting performance in memory-intensive scenarios but enabling seamless operation within Java ecosystems. This JVM-centric design facilitates full interoperability with Java, where Jython code is compiled directly to JVM bytecode, permitting Python scripts to import and instantiate Java classes without wrappers or bridges—for instance, a Jython program can directly use from java.util import ArrayList to leverage Java's collections framework alongside Python's dynamic typing. Conversely, CPython requires external tools or processes for Java interaction, limiting its integration in mixed-language environments.[9][5]
Jython's relationship with Java extends to bidirectional embedding, allowing Java applications to invoke Jython interpreters and execute Python code as scripts or modules, often through mechanisms like the PythonInterpreter class or JSR-223 scripting engine for dynamic loading. This symbiosis positions Jython as a bridge for utilizing Python's concise, readable syntax—typically 2 to 10 times shorter than equivalent Java code—for rapid prototyping and scripting within Java-dominated domains, such as enterprise software development, while granting access to the vast Java library ecosystem without recompilation. By running on the JVM, Jython inherits Java's portability across platforms and security features, enhancing Python's applicability in large-scale, production Java systems.[1][9]
History
Origins and early development
Jython, originally known as JPython, was created by Jim Hugunin in the spring of 1997 while he was pursuing his PhD in electrical engineering at the Massachusetts Institute of Technology (MIT).[10] Hugunin had been working on Numeric Python, an extension to Python for numerical computations inspired by MATLAB, which relied on C extensions that suffered from performance inconsistencies across platforms and machines.[10] During benchmarking efforts for Numeric Python, Hugunin discovered the superior speed and portability of Java, particularly with the HotSpot JVM, leading him to develop JPython as a Python implementation in Java to replace C-based extensions with more efficient, cross-platform alternatives.[10] This approach also enabled direct access to Java libraries from Python code, addressing limitations in extending Python for scientific computing.[10]
Following the project's inception, Hugunin joined the Corporation for National Research Initiatives (CNRI) later in 1997, where he collaborated with Python's core developers, including Guido van Rossum.[11] The initial release, JPython 1.0, occurred in late 1997, coinciding with Hugunin's presentation on the project at the 6th International Python Conference in October.[10] Development at CNRI was supported in part by funding from the organization itself and through a DARPA grant aimed at mobile agent research, which indirectly advanced Python-related initiatives like JPython.[11]
Hugunin departed CNRI in early 1999 to join Xerox PARC and work on AspectJ, after which Barry Warsaw assumed leadership as primary developer and released JPython 1.1 in February 1999.[3] In October 2000, as Warsaw and the PythonLabs team transitioned away from CNRI, the project was relocated to SourceForge, where it was renamed Jython to reflect its growing emphasis on open-source collaboration and community-driven development.[2] This renaming, under Warsaw's guidance, marked a pivotal shift toward broader accessibility and maintenance by a distributed group of contributors.[3]
Key releases and transitions
Jython 2.0 was released in January 2001, marking full alignment with CPython 2.0 and introducing support for Python's evolving standard library while maintaining seamless interoperability with Java classes.[12] Subsequent releases in the 2.x series continued this synchronization, with Jython 2.1 arriving in December 2001 to incorporate refinements in exception handling and Unicode support from CPython.[5] By August 2007, Jython 2.2 brought new-style classes, PEP 302 import hooks, and improved integration with Java collections, such as enhanced support for Java List interfaces, reflecting adaptations to Java 5 features like generics and iterable enhancements.[13]
Further advancements came with Jython 2.5 in June 2009, which mirrored CPython 2.5 by adding with-statements for resource management and absolute imports, alongside better handling of Java 6 concurrency utilities in the standard library.[14] The 2.7 series began with Jython 2.7.0 in May 2015, aligning closely with CPython 2.7 and including improvements in syntax for set literals and dictionary comprehensions, while optimizing bytecode generation on the JVM.[15] This was followed by maintenance releases: 2.7.1 in July 2017, focusing on bug fixes and compatibility; 2.7.2 in March 2020, with further stability enhancements; 2.7.3 in September 2022; and 2.7.4 in August 2024, the latest as of November 2025, continuing to support CPython 2.7 compatibility on modern JVMs.[16] Throughout these releases, the intellectual property rights for Jython have been held and managed by the Python Software Foundation, providing structured governance and licensing continuity.[17]
A key transition in Jython's evolution involved adopting oversight from the Python Software Foundation, which ensured consistent licensing under the PSF terms starting from the 2.2 release onward, fostering community contributions while preserving compatibility.[18] However, maintaining pace with CPython's rapid feature additions posed ongoing challenges, primarily due to the complexities of reimplementing Python semantics on the JVM, resulting in inherent time lags between corresponding releases.[19] These constraints, including the need to adapt C-based extensions to Java equivalents, limited the frequency of major updates but highlighted Jython's strengths in enterprise Java environments.
Technical foundations
Implementation on the JVM
Jython implements Python by parsing source code into an Abstract Syntax Tree (AST) and compiling it directly into JVM bytecode, which allows execution on the Java Virtual Machine without relying on a C-based interpreter like CPython. This process begins with the parser, which analyzes Python syntax and constructs the AST representing the code's structure, followed by the compiler that translates this AST into platform-independent JVM instructions. Unlike CPython's approach of interpreting bytecode through a custom virtual machine, Jython's compilation enables seamless integration with the JVM's execution model, where the resulting bytecode is loaded and run just like native Java code.[8][6]
The runtime environment of Jython fully leverages the JVM's core services, including automatic garbage collection for memory management, multi-threading capabilities without a Global Interpreter Lock (GIL), and the built-in security manager for sandboxed execution. Python objects are mapped to corresponding Java classes, with the PyObject superclass serving as the foundational representation for all Python values, attributes, and methods in the Java ecosystem. This mapping ensures that Python's object model operates within Java's type system, allowing for efficient invocation of Python code from Java and vice versa through the org.python.core package. The runtime library, which includes essential modules for file I/O, exceptions, and built-ins, is largely adapted from CPython but rewritten in pure Java to ensure compatibility with the JVM's constraints and optimizations.[8][1][20]
To accommodate Python's dynamic features, such as runtime type changes and method overriding, Jython employs Java's reflection API to inspect and modify object states dynamically, alongside dynamic proxies for emulating Python's flexible attribute access and descriptor protocols. For instance, the PyObject hierarchy uses reflection to handle method resolution and attribute lookup at runtime, bridging the gap between Python's duck typing and Java's static typing. This architecture avoids the need for a separate Python-specific virtual machine, instead embedding Python semantics directly into the JVM's just-in-time compilation and optimization pipeline.[8][6]
Compatibility with CPython
Jython provides full support for the Python 2.7 language specification, including its syntax, semantics, and core features, ensuring that standard Python code written for CPython 2.7 can generally run unchanged in Jython.[5] This compatibility extends to nearly all modules in the Python 2.7 standard library, with some modules adapted to use Java equivalents for system interactions, such as os and sys, which leverage JVM capabilities for file handling and platform-specific operations.[5][21]
Despite this alignment, Jython has notable limitations compared to CPython due to its JVM-based implementation. It does not support C extensions, which are common in CPython for performance-critical libraries like NumPy; instead, Jython requires pure Python alternatives or Java-based implementations for such functionality.[5] Additionally, some standard library modules exhibit incomplete support stemming from JVM differences, including variances in the threading model—Jython lacks CPython's Global Interpreter Lock (GIL) and uses Java's native threading, potentially affecting code reliant on GIL behavior—and restrictions in I/O operations, multiprocessing (limited by the absence of Unix-like fork semantics), and Unicode handling, where Jython's Python-based unicodedata module performs slower than CPython's C implementation.[5][22][23]
To maintain compatibility, the Jython project employs strategies such as backporting and adapting CPython's regression test suite, with modifications to account for JVM-specific behaviors, and actively addresses discrepancies in areas like I/O, multiprocessing, and Unicode through ongoing refinements.[5][15] Jython's version alignment remains tied to Python 2.7, with the current release (2.7.4 as of 2025) matching CPython 2.7, while Python 3.x support remains unavailable and is targeted for future development.[7][5]
Features and capabilities
Java-Python integration
Jython facilitates seamless integration between Python and Java by allowing Python code to directly access and utilize Java classes, methods, and objects, enabling developers to leverage the extensive Java ecosystem within Python scripts.[9] One primary mechanism is importing Java classes into Jython using familiar Python import syntax, such as from java.util import ArrayList, which treats Java packages as Python modules.[24] This import process supports both full package imports (e.g., import java.lang) and specific class imports, allowing instantiation and method calls as if they were native Python objects—for instance, creating an ArrayList instance with al = ArrayList() and adding elements via al.add("item").[9]
To ensure interoperability, Jython performs automatic type conversions between Python and Java data types, minimizing manual bridging efforts. For example, Python lists are transparently converted to Java arrays when passed to Java methods expecting array parameters, such as converting [1, 2, 3] to an int[] for a method like Arrays.sort(). Conversely, Java primitives like int become Python int objects, Java String maps to Python str, and Java collections like List are iterable in Python as sequences.[9] These conversions handle common cases bidirectionally, though more complex structures may require explicit wrapping using Jython's PyObject or Java's reflection APIs.[25]
Embedding Jython within Java applications provides a way to execute Python scripts dynamically from Java code, useful for scenarios like configuration scripting or plugin systems. This is achieved primarily through the PythonInterpreter class from the org.python.util package, which initializes a Python execution context and runs code via methods like exec(). For instance, a Java application can create an interpreter with PythonInterpreter interp = new PythonInterpreter();, execute a script such as interp.exec("x = 2 + 2");, and retrieve results using PyObject result = interp.get("x");.[25] Alternatively, the JSR-223 scripting API standardizes this embedding by loading Jython as a script engine: ScriptEngine engine = new ScriptEngineManager().getEngineByName("python"); engine.eval("print('Hello from Python')");, requiring the jython-standalone.jar and jython-engine.jar on the classpath.[9] The PySystemState class offers a lower-level alternative for custom initialization, often used in high-performance scenarios to manage the Python runtime state without a full interpreter.[9]
Extending Java functionality with Python allows Jython users to subclass Java classes and override their methods, blending Python's dynamic nature with Java's static structure. Subclassing follows standard Python syntax, such as class MyActionListener(java.awt.event.ActionListener): def actionPerformed(self, event): print("Action triggered"), where the Python method overrides the Java interface's actionPerformed.[25] Superclass methods can be invoked explicitly with self.actionPerformed_super(event) or via Python's super() for protected access. For handling overloaded Java methods, Python subclasses use variable arguments like *args to match multiple signatures dynamically.[25] Additionally, Jython enables access to JVM internals from Python through Java's reflection API; for example, importing java.lang.reflect allows inspecting and invoking private methods or fields by setting the system property python.security.respectJavaAccessibility=false to bypass access checks.[25]
To bridge the gap with CPython's native C extensions, which Jython does not natively support due to its JVM-based implementation, the experimental JyNI (Jython Native Interface) tool provides a compatibility layer. JyNI translates CPython's C API calls to Java equivalents, allowing Jython to load and use extensions like NumPy or SciPy by placing the library on the Java classpath during Jython startup.[26] This enables scientific computing libraries in Jython environments, though the project was last updated in 2017 and may not cover all edge cases of the C extension API.[27][28]
Unique Jython features
Jython's interactive console, accessible via the jython command, provides an enhanced development experience through its integration with JVM-based debugging tools, allowing developers to leverage Java's robust ecosystem for troubleshooting Python code running on the JVM.[29] This includes compatibility with Java profilers such as VisualVM, which can monitor and profile Jython applications in real-time, capturing CPU usage, memory allocation, and thread activity without requiring modifications to the Python code.[30]
In terms of performance, Jython typically executes pure Python code 2-10 times slower than CPython due to the overhead of JVM interpretation and just-in-time compilation, though it excels in scenarios involving heavy use of Java libraries where the JVM's optimizations provide significant speedups.[31] The 2.7.x series introduced key optimizations, including improved method invocation that boosted benchmark performance—such as a 3x speedup on the Richards benchmark and 20% on Pystone compared to 2.5.x—along with reduced startup times through better initialization routines.[32] Jython also employs bytecode caching mechanisms, compiling Python scripts to Java .class files via the compileall module, which stores optimized bytecode for faster subsequent loads, and maintains a package cache for Java imports to minimize runtime discovery overhead.[33][34]
Jython includes specialized modules for deeper JVM interaction, such as the PyJavaInstance class, which wraps Java objects to enable dynamic creation and manipulation of instances directly in Python code, facilitating seamless type conversions and attribute access.[35] Additionally, tools like the Clamp project and jannotation module allow Python code to incorporate Java annotations, automatically generating compatible Java classes from annotated Jython scripts for enhanced interoperability in mixed-language environments.[9][36]
In enterprise settings, Jython supports hot deployment within application servers like Tomcat, where Python scripts can be updated and reloaded without restarting the server, leveraging the container's classloading capabilities for rapid iteration in web applications.[37] It also integrates smoothly with frameworks such as Spring, enabling Python components to be wired into Java-based dependency injection and configuration systems.[38] For mobile development, Jython offers limited support on Android via compatibility with the Dalvik/ART runtime, though it faces constraints from missing Java APIs and requires custom bridging for full functionality.[39]
Development status
Current versions
As of November 2025, the latest stable release of Jython is version 2.7.4, issued in August 2024, which provides full compatibility with Python 2.7 while incorporating bug fixes and enhancements tailored for integration with the Java Virtual Machine (JVM).[16] This version maintains backward compatibility with earlier Python 2.7 releases but addresses specific issues encountered in JVM environments, such as an IndexError when accessing sys.argv and updates to JAR dependencies for better reliability.[40]
Jython 2.7.4 supports JVM versions starting from Java 8 as the minimum requirement, with official testing conducted on Java 11; due to Java's strong backward compatibility, it functions on later versions including Java 17 and 21 without modification.[7] Binary installers, distributed as standalone JAR files, are available for cross-platform deployment on Windows, macOS, and Linux, enabling seamless execution wherever a compatible JVM is present.[7]
Key recent updates in this release include security patches mitigating vulnerabilities in underlying libraries, such as CVE-2024-25710 and CVE-2024-26308 in Apache Commons Compress, and an upgrade to Google Guava 32.0.1 to resolve CVE-2023-2976.[40] Standard library compatibility has been refined with additions like exporting xml.parsers and xml.etree in xml.all, and updating the ucnhash.dat file to Unicode 15.1 for improved internationalization handling.[40] Development occurs via the community-maintained GitHub repository, established in 2015, ensuring ongoing fixes and features for the Python 2.7 implementation, though no official Python 3 release exists yet.[6][1]
Future roadmap
The Jython 3 project aims to deliver a minimum viable product (MVP) with core compatibility to Python 3.8, including full syntax support, execution of CPython bytecode, seamless Java object integration treated as Python objects, a module import system aligned with CPython, and a compiler translating Python source to abstract syntax trees (AST) and bytecode, alongside a console for major operating systems.[41][42] This effort targets near-complete porting of the Python standard library, excluding modules reliant on C-specific implementations, with progressive integration supported by regression testing to ensure fidelity.[41] Challenges in this development include achieving performance parity with CPython—aiming for results within a factor of two—while addressing concurrency differences arising from the absence of a Global Interpreter Lock (GIL) on the JVM, which impacts features like async/await, and handling Unicode through JVM-native mechanisms.[42]
Ongoing work tracked in the project's GitHub repository focuses on restructuring the codebase using Gradle for builds, implementing a modern type system, interpreters, and descriptor protocols, alongside adopting a PEG parser and Java MethodHandles for efficiency.[41][6] Milestones emphasize porting the standard library incrementally and enhancing emulation of C extensions, primarily through JyNI (Jython Native Interface), a compatibility layer that exposes CPython's C API atop Jython to enable loading native extensions like NumPy without full reimplementation.[42][43] Alternative bridges, such as those leveraging GraalVM's polyglot capabilities, are explored for improved interoperability, though Jython maintains its distinct path.[42][44]
Community objectives prioritize JVM-specific optimizations for better runtime performance, including potential future compilation to JVM bytecode, and deeper integration with modern Java features like modules introduced in Java 9 and beyond to streamline hybrid Java-Python applications.[41][42] There is also interest in potential synergies or convergence with other JVM-based Python implementations, such as GraalPython, to address overlapping goals in Python 3 support on the JVM while preserving Jython's unique Java-centric strengths.[45]
Development faces roadblocks stemming from limited resources following the Python 2 end-of-life in 2020, which has shifted emphasis toward sustaining Jython 2.7 for legacy needs while advancing Jython 3 at a measured pace, concentrating on niche use cases in Java-Python hybrid environments like scientific computing and enterprise scripting.[1][46] Progress remains exploratory in the main GitHub branch, with no firm release timelines announced as of late 2025.[6]
Licensing and distribution
License details
Jython's source code and binaries are primarily governed by the Python Software Foundation License version 2 (PSF v2), a permissive open-source license approved by the Open Source Initiative (OSI) that permits commercial and non-commercial use, modification, and distribution with attribution.[18] This license applies to Jython releases from version 2.2 onward, ensuring broad accessibility for integration into various software ecosystems.[18]
Historically, the project evolved through different licensing terms: early versions known as JPython (up to 1.1.x) were released under the CNRI License Agreement, a custom permissive license developed by the Corporation for National Research Initiatives; Jython 2.0 and 2.1 operated under a Jython-specific license that maintained similar royalty-free terms but with distinct wording.[18] Additionally, the command-line interpreter component has been licensed separately under the Apache License 2.0, which also supports permissive use while requiring preservation of Apache notices.[18] The standard library follows the PSF v2, while certain modules like zxJDBC transitioned from the GNU General Public License to the Jython Software License to align with the project's overall terms.[18]
Key conditions under the PSF v2 include the requirement to retain all original copyright notices—such as "Copyright © 2001, Python Software Foundation; All Rights Reserved"—in redistributions and derivative works, along with providing a summary of changes made.[18] The software is provided "as is" without any warranties, express or implied, and the licensor disclaims liability for any damages arising from its use.[18] PSF v2 is compatible with the GNU General Public License (GPL) through explicit clauses allowing distribution of combined works, facilitating interoperability with GPL-licensed software.
These licensing terms enable developers to embed Jython in proprietary Java applications without incurring licensing fees, promoting its adoption in enterprise environments while ensuring contributor protections through agreements that grant the Python Software Foundation rights to relicense contributions.[18]
Availability and installation
Jython is available for download from its official website at jython.org, where the current stable release, version 2.7.4, can be obtained as a standalone installer JAR file (jython-installer-2.7.4.jar) for local installation or as a standalone JAR (jython-standalone-2.7.4.jar) for running without full installation or embedding in Java applications.[7] Source code and development builds are accessible via the official GitHub repository at github.com/jython/jython, allowing users to clone the repository for building from source using tools like Ant or Gradle.[6]
The minimum system requirement for Jython is a Java 8 JDK or JRE, with compatibility tested up to Java 11; while it supports both 32-bit and 64-bit architectures, 64-bit Java installations are recommended for better performance on modern systems.[7] There are no platform-specific binaries beyond platform-appropriate launcher scripts (e.g., jython for Unix-like systems and jython.exe for Windows), as the core distribution relies on the cross-platform JAR format.[47]
To install Jython, download the installer JAR from the official site and execute it using the command java -jar jython-installer-2.7.4.jar (or java -jar jython-installer-2.7.4.jar --console for a headless mode), which launches a GUI or console wizard to accept the license, select an installation directory, choose the JVM, and complete the file setup.[7][47] After installation, add the bin directory (e.g., /opt/jython2.7.4/bin on Unix-like systems or C:\jython2.7.4\bin on Windows) to the system PATH to enable the jython command.[47]
Installation can be verified by running jython from the command line, which should start the interactive console if the interpreter is correctly configured and accessible.[47]
Applications and usage
Common use cases
Jython is particularly valued in enterprise environments for scripting administrative tasks on Java-based application servers. For instance, IBM WebSphere Application Server employs Jython through its wsadmin tool to automate server configuration, deployment, and management operations, enabling administrators to perform complex tasks like starting or stopping applications and monitoring resources without relying on the administrative console.[48] In modern versions of WildFly (the successor to JBoss Application Server), Jython can be used for management scripting via the CLI, allowing users to leverage Python's concise syntax to interact with the server's management model, such as deploying applications or configuring datasources, while benefiting from the JVM's robustness.[49]
In data processing workflows, Jython facilitates extract, transform, and load (ETL) processes within Java-centric big data ecosystems like Hadoop. Apache Pig, a high-level platform for analyzing large datasets in Hadoop, supports user-defined functions (UDFs) written in Jython, enabling developers to extend Pig scripts with custom Python logic that compiles to Java bytecode for seamless execution on the cluster, thus combining Python's data manipulation ease with Hadoop's scalability.[50]
Jython excels in rapid prototyping of Java extensions and user interfaces, where its Python-like simplicity accelerates development before transitioning to full Java implementations. Developers can prototype algorithms, object models, or entire applications in Jython, directly accessing Java classes and libraries, which often results in code that is 2-10 times shorter than equivalent Java, allowing for quick iteration and validation in JVM environments.[51] This approach has been demonstrated in educational and practical projects, such as extending Java-based systems with Python scripts for UI components or business logic, minimizing the boilerplate code typical in pure Java prototyping.[52]
In scientific image processing, Jython is widely used in ImageJ and Fiji for scripting macros and automating image analysis workflows. It allows researchers to write Python scripts that interact with ImageJ's Java APIs for tasks like filtering, segmentation, and visualization, providing a more readable alternative to Java code while maintaining performance on the JVM.[53]
For legacy integration, Jython serves as a bridge to migrate and enhance older Python scripts in mixed-language systems running on the JVM, improving performance through bytecode compilation without full rewrites. It allows embedding legacy Python code into Java applications, such as running scripts for automation or data handling alongside Java components.[51] This capability is especially useful in enterprise settings where existing Python investments need to coexist with Java infrastructure for better resource utilization and scalability.[1]
Getting started examples
To get started with Jython, developers can execute simple Python scripts using the jython command-line tool, which launches the interpreter on the Java Virtual Machine (JVM).[20] For a basic example, create a file named hello.py containing the following code:
python
print("Hello, Jython!")
print("Hello, Jython!")
Run it from the command line with jython hello.py, which outputs "Hello, Jython!" to the console.[54] This demonstrates Jython's compatibility with standard Python syntax for standalone scripts.[20]
Jython also supports an interactive mode via the Read-Eval-Print Loop (REPL), allowing immediate experimentation with Python built-ins. Launch it by typing jython in the terminal, then enter commands such as:
python
>>> [print](/page/Print)("Jython REPL")
Jython REPL
>>> [len](/page/LEN)("hello")
5
>>> [print](/page/Print)("Jython REPL")
Jython REPL
>>> [len](/page/LEN)("hello")
5
This REPL behaves like CPython's but operates within the JVM environment.[54]
For basic Java integration, Jython enables direct import and use of Java classes from Python code. A simple example prints the JVM version:
python
from java.lang import System
print(System.getProperty('java.version'))
from java.lang import System
print(System.getProperty('java.version'))
Executing this snippet via jython -c "from java.lang import System; print(System.getProperty('java.version'))" reveals the running Java version, such as "11.0.21", highlighting Jython's seamless access to Java APIs.[20]
To embed Jython within a Java application, use the PythonInterpreter class from the Jython library. The following Java code initializes an interpreter and executes a Python string:
java
import org.python.util.PythonInterpreter;
public class EmbedExample {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.exec("print('Embedded Jython')");
}
}
import org.python.util.PythonInterpreter;
public class EmbedExample {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.exec("print('Embedded Jython')");
}
}
Compile and run this with javac -cp jython-standalone-2.7.4.jar EmbedExample.java followed by java -cp .:jython-standalone-2.7.4.jar EmbedExample, producing the output "Embedded Jython". This approach allows Java programs to leverage Python scripting dynamically.[54][20]