Embedding Jython in Java

Your Java-coded application can embed the Jython interpreter in order to use Jython for scripting. jython.jar must be in your Java CLASSPATH. Your Java code must import org.python.core.* and org.python.util.* in order to access Jython’s classes. To initialize Jython’s state and instantiate an interpreter, use the Java statements:

PySystemState.initialize( );
PythonInterpreter interp = new PythonInterpreter( );

Jython also supplies several advanced overloads of this method and constructor in order to let you determine in detail how PySystemState is set up, and to control the system state and global scope for each interpreter instance. However, in typical, simple cases, the previous Java code is all your application needs.

The PythonInterpreter Class

Once you have an instance interp of class PythonInterpreter, you can call method interp .eval to have the interpreter evaluate a Python expression held in a Java string. You can also call any of several overloads of interp .exec and interp .execfile to have the interpreter execute Python statements held in a Java string, a precompiled Jython code object, a file, or a Java InputStream.

The Python code you execute can import your Java classes in order to access your application’s functionality. Your Java code can set attributes in the interpreter namespace by calling overloads of interp .set, and get attributes from the interpreter namespace by calling overloads of interp .get. The methods’ overloads give you a ...

Get Python in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.