InteractiveConsole and namespace

David ROBERT david at ombrepixel.com
Sat Aug 28 17:37:39 EDT 2010


Hi all,

I want to use an InteractiveConsole at some stage in a program to
interact with the local namespace: access, but also modify objects.
When the interactive console ends (ctrl-d) I want the program to
continue processing with the variables that may have been modified
interactively.

The code below works (block invoking the console is not in a
function). During the interactive session, I can read value of a, I
can change value of a and the new value is "updated" in the block
namespace.

import code
if __name__ == '__main__':
    a=1
    c = code.InteractiveConsole(locals())
    c.interact()  # Here I interactively change the value of a (a=2)
    print "Value of a: ", a

print returns --> Value of a: 2

However, on the other code below (the console is invoked from within a
function block), during the interactive session, I can read value of
a, I can change value of a. But the local namespace of the function is
not updated:

import code
def test():
    a=1
    c = code.InteractiveConsole(locals())
    c.interact() # Here I interactively change the value of a (a=2)
    print "Value of a: ", a

if __name__ == '__main__':
    test()

print returns --> Value of a: 1

I need to run the InteractiveConsole from a function block. I tried
different things with the local and parent frames (sys._getframe())
but nothing successful. If I put a in the global namespace it works,
but I would like to find a nicer solution and also understand what the
problem is.

Thanks for any help

-- 
David ROBERT
http://blog.ombrepixel.com/



More information about the Python-list mailing list