Home www.python.org
Download Documentation
Home
Overview
License
Jython 2.0
Jython 2.1
Installing
JVM Compatibility
 
Documentation
Overview
Executive Summary
Invoking Jython
Jython Registry
Embedding
Compiling Jython from source
 
Working with Java
The Basics
JavaBean Properties
Java arrays
Subclassing
Building applets, servlets, beans...
Reloading java classes
zxJDBC
 
Python Docs (exits)
Python Tutorial
Library Reference
 
Other
Jython vs. CPython
Jython FAQ
List Archives (exit)
JPython paper (exit)
 
Email Us
jython-dev@lists.sourceforge.net
 
 
SourceForge Logo
  

Embedding Jython

There are several options for embedding Jython in a Java application. Sometimes the nicest approach is to make a real Java class out of a Python class and then just use that Python class from Java code. The simplest approach to embedding Jython is to use the PythonInterpreter object.

JavaDoc documentation for org.python.util.PythonInterpreter
The following example is distributed under Demo/embed/SimpleEmbedded.java


import org.python.util.PythonInterpreter; 
import org.python.core.*; 

public class SimpleEmbedded { 
    public static void main(String []args)
	throws PyException
    { 
	PythonInterpreter interp =
	    new PythonInterpreter();

	System.out.println("Hello, brave new world");
	interp.exec("import sys");
	interp.exec("print sys");

	interp.set("a", new PyInteger(42));
	interp.exec("print a");
	interp.exec("x = 2+2");
	PyObject x = interp.get("x");

	System.out.println("x: "+x);
	System.out.println("Goodbye, cruel world");
    }
}