At our last meeting, I mentioned my use of python as a utility
to make a Java application "programmable". There seemed to
be some interest in this technique. I used this technique in a
web app I built for one of my clients. They needed to change
formulas for calculating aluminium window frame sizes without having
me involved. Sometime the calculating formula would change
by 0.25 of an inch…
So, here is a technique where python interpreter is embedded
in Java code, the Java then for the sake of this demo, sets
a object in Python called X - does a little bit of manipulation
of it on the Python interpreter, and then, sets a variable of
the executing class SimpleEmbedded via "this" - and then
execute a callback from Python back into Java… This very
cool feature alone, makes the Jython interpreter very versatile
(and potentially dangerous)…
PyObject shown below is the most primitive Object that
can be easily cast if need be into other objects… Python
also does have an eval() function which can lead to other
very interesting and convoluted possibilities...
References:
Embedding Python in Lisp (maybe somebody really well versed in lisp can try it??)
http://common-lisp.net/project/python-on-lisp/
==============================================
Sample running code…
==============================
File: SimpleEmbedded.java
import org.python.util.PythonInterpreter;
import org.python.core.*;
public class SimpleEmbedded {
// this method below will be called back by the Python interpreter
public void nasty(Object PyObject) {
System.out.println(" python sez - "+PyObject);
}
public SimpleEmbedded() {
PythonInterpreter interp = new PythonInterpreter();
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);
interp.set("myjavaclass", this); //YEAH BABY... very cool here.. set
Python object myjavaclass the "address" of this object - a callback of
sorts
interp.execfile("c:/test.py");
}
public static void main(String []args) throws PyException {
SimpleEmbedded se = new SimpleEmbedded();
}
}
==============================
Test.py
### Variable x has been set by the Java program to the inerpreter..
## just a little simple math for the sake of the demo
num = x*4
## Calling BACK the Java method nasty -- the ability to do this gives
## us the ability to build very very complex 5gen type very high level
## utilities that analysts and other non-programmers can use..
myjavaclass.nasty(num)
==============================
Output on console... below
<module 'sys' (built-in)>
42
x: 4
python sez - 16