Chris Rebert <c...@rebertia.com> writes: > On Sat, Aug 28, 2010 at 2:37 PM, David ROBERT <da...@ombrepixel.com> wrote: >> 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. >> [...] >> 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 > [...] >> understand what the >> problem is. > > Read http://docs.python.org/library/functions.html#locals (emphasis added): > > "locals() > [...] > Note: The contents of this dictionary should not be modified; [...]
Here is a solution: def test(): a=1 loc = dict(locals()) c = code.InteractiveConsole(loc) c.interact() # Here I interactively change the value of a (a=2) for key in loc: if key != '__builtins__': exec "%s = loc[%r]" % (key, key) print "Value of a: ", a HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list