Jython is an implementation of Python 2.7 written in 100% Pure Java, providing seamless integration with the Java platform and ecosystem.
—
Jython provides multiple approaches for executing Python code from Java applications, ranging from simple script execution to full interactive interpreters.
The main interface for embedding Python code execution in Java applications.
public class PythonInterpreter implements AutoCloseable, Closeable {
// Constructors
public PythonInterpreter();
public PythonInterpreter(PyObject dict);
public PythonInterpreter(PyObject dict, PySystemState systemState);
public static PythonInterpreter threadLocalStateInterpreter(PyObject dict);
// Code execution
public void exec(String code);
public void exec(PyCode code);
public void execfile(String filename);
public PyObject eval(String code);
public PyObject eval(PyCode code);
// Variable management
public void set(String name, Object value);
public void set(String name, PyObject value);
public PyObject get(String name);
public PyObject get(String name, PyObject defaultValue);
// I/O management
public void setOut(java.io.Writer outStream);
public void setOut(PyObject outStream);
public void setErr(java.io.Writer errStream);
public void setErr(PyObject errStream);
public void setIn(java.io.Reader inStream);
public void setIn(PyObject inStream);
// Namespace management
public PyObject getLocals();
public void setLocals(PyObject locals);
public PyObject getGlobals();
public void setGlobals(PyObject globals);
// System state access
public PySystemState getSystemState();
// Resource management
public void close();
public void cleanup();
}PythonInterpreter interp = new PythonInterpreter();
// Execute simple Python code
interp.exec("print('Hello, World!')");
interp.exec("x = 2 + 3");
// Get result
PyObject result = interp.get("x");
System.out.println("Result: " + result.asInt()); // Output: 5
interp.close();PythonInterpreter interp = new PythonInterpreter();
// Set Java variables in Python
interp.set("name", "Alice");
interp.set("age", 30);
// Execute Python code using those variables
interp.exec("""
greeting = f"Hello, {name}! You are {age} years old."
birth_year = 2024 - age
""");
// Get results back to Java
String greeting = interp.get("greeting").toString();
int birthYear = interp.get("birth_year").asInt();
System.out.println(greeting); // Hello, Alice! You are 30 years old.
System.out.println(birthYear); // 1994
interp.close();PythonInterpreter interp = new PythonInterpreter();
// Execute Python file
interp.execfile("/path/to/script.py");
// Access variables defined in the file
PyObject result = interp.get("some_variable");
interp.close();Supports interactive Python console functionality with proper handling of incomplete statements.
public class InteractiveInterpreter extends PythonInterpreter {
public InteractiveInterpreter();
public InteractiveInterpreter(PyObject locals);
public InteractiveInterpreter(PyObject locals, PySystemState systemState);
// Interactive execution
public boolean runsource(String source);
public boolean runsource(String source, String filename);
public boolean runsource(String source, String filename, CompileMode mode);
// Code execution
public void runcode(PyObject code);
// Compilation
public PyCode compile(String source, String filename, CompileMode mode);
// Error handling for interactive use
public void showexception(PyException exc);
public void showtraceback();
public void showsyntaxerror(String filename);
// Output methods
public void write(String data);
// Buffer management
public StringBuilder buffer;
public void resetbuffer();
// Debugging support
public void interrupt(ThreadState ts);
}InteractiveInterpreter interp = new InteractiveInterpreter();
// Returns true if more input is needed (incomplete statement)
boolean needsMore = interp.runsource("if True:");
System.out.println(needsMore); // true
// Complete the statement
needsMore = interp.runsource(" print('Complete!')");
System.out.println(needsMore); // false - statement executed
interp.close();Complete interactive Python console with input/output handling.
public class InteractiveConsole extends InteractiveInterpreter {
public InteractiveConsole();
public InteractiveConsole(PyObject locals);
public InteractiveConsole(PyObject locals, String filename);
// Console interaction
public void interact();
public void interact(String banner);
public String raw_input();
public String raw_input(PyObject prompt);
// Input handling
public boolean push(String line);
public void resetbuffer();
}InteractiveConsole console = new InteractiveConsole();
// Start interactive session with custom banner
console.interact("Welcome to Jython Console!");
// This will start an interactive Python REPL that accepts input
// and provides output until the user exitsRepresent compiled Python code that can be executed multiple times.
public abstract class PyCode extends PyObject {
public abstract PyObject call(ThreadState ts, PyFrame frame);
public PyObject call(PyObject globals);
public PyObject call(PyObject globals, PyObject locals);
}
// Factory methods in Py class
public final class Py {
public static PyCode newCode(int argcount, String varnames[],
String filename, String name,
boolean args, boolean keywords,
PyFunctionTable funcs, int func_id);
public static PyCode newJavaCode(Class<?> cls, String name);
}PythonInterpreter interp = new PythonInterpreter();
// Compile code once
PyCode code = interp.compile("result = x * y + z", "<string>", CompileMode.exec);
// Execute multiple times with different variables
interp.set("x", 2);
interp.set("y", 3);
interp.set("z", 4);
interp.eval(code);
System.out.println(interp.get("result")); // 10
interp.set("x", 5);
interp.set("y", 6);
interp.set("z", 7);
interp.eval(code);
System.out.println(interp.get("result")); // 37
interp.close();public class PythonInterpreter {
public static void initialize(Properties preProperties,
Properties postProperties,
String[] argv);
}Properties preProps = new Properties();
preProps.setProperty("python.home", "/path/to/jython");
Properties postProps = new Properties();
postProps.setProperty("python.path", "/path/to/modules:/another/path");
String[] args = {"arg1", "arg2"};
PythonInterpreter.initialize(preProps, postProps, args);
PythonInterpreter interp = new PythonInterpreter();
// Interpreter now uses custom configuration
interp.close();public class PythonInterpreter {
public static PythonInterpreter threadLocalStateInterpreter(PyObject dict);
}// Create thread-local interpreter
PythonInterpreter interp = PythonInterpreter.threadLocalStateInterpreter(null);
// Each thread gets its own interpreter instance
// Safe for concurrent use across threads
interp.exec("print('Thread:', threading.current_thread().name)");
interp.close();// Try-with-resources (recommended)
try (PythonInterpreter interp = new PythonInterpreter()) {
interp.exec("print('Hello, World!')");
// Automatically closed
}
// Manual cleanup
PythonInterpreter interp = new PythonInterpreter();
try {
interp.exec("print('Hello, World!')");
} finally {
interp.close();
}All execution methods can throw PyException for Python runtime errors:
try {
interp.exec("undefined_variable");
} catch (PyException e) {
if (e.match(Py.NameError)) {
System.out.println("Variable not found: " + e.value);
}
}Install with Tessl CLI
npx tessl i tessl/maven-org-python--jython-standalone