Well, I could not find the relevant code in PyScriptEngineScope to fetch all the locals. But, I modified my code as follows.

I created a class KeyValueMap

class KeyValueMap extends PyStringMap {

    public KeyValueMap() {

    public PyObject keyToPyObject(Object objKey) {
        if (objKey instanceof String) {
            return PyString.fromInterned((String)objKey);
        } else {
            return (PyObject)objKey;

I had to copy the code of method "keyToPy" and make it public since it is private in PyStringMap.

Run the source code as follows

KeyValueMap keyValueMap = new KeyValueMap();
PythonInterpreter interp = new PythonInterpreter(keyValueMap);

And then print the output as follows

PyList keyList = keyValueMap.keys();
for (Object key : keyList) {
    PyObject value = keyValueMap.get(keyValueMap.keyToPyObject(key));
    if (!(key.equals("__name__") || key.equals("__doc__") || key.equals("sys") || key.equals("math"))) {
        System.out.println(key + " = " + value + "\n");

It works. :) and is cleaner than my previous attempt. I could have tracked __finditem__ and __setitem__ if I wanted to monitor the
values during the execution of the script, but the above code does my job.

Thanks again.

On Tue, Mar 2, 2010 at 5:16 PM, Nicholas Riley <njriley@illinois.edu> wrote:
In article
 Marc Downie <marc@openendedgroup.com> wrote:

> What we do: when you make a PythonInterpreter pass in your own subclass of
> PyStringMap to act as the globals space for that interpreter. Track set's
> and get's by overriding __finditem__ and __setitem__.

That's a better idea than what I suggested.  You don't even need to
subclass PyStringMap; you could create your own class that supports the
Jython mapping interface.

Again, you can look at an example in the JSR 223 interface, which
actually does more than you need:
Nicholas Riley <njriley@illinois.edu>