InteractiveConsole locals parameter, solved, but UGLY!

Bruce Edge bedge at troikanetworks.com
Thu Mar 22 16:18:58 EST 2001


I found a way to do it, but, tell me there's a cleaner way:

change the run_python() as follows

def run_python():
  banner = "Use Ctrl-D to exit python and return to CLI"	
  import code
  import __main__
  locals = __main__.__dict__
  x = code.InteractiveConsole(locals)
  x.locals.update( { "run_python": run_python } ) <-- add this line !!!! 
  x.interact( banner )


In short, you have to manually add items to the namespace. At least this
is true for items which the application creates.

In article <3AB7FE07.5F7584F5 at troikanetworks.com>, "Bruce Edge"
<bedge at troikanetworks.com> wrote:

> I can't get my __main__.__dict__ passed to an InteractiveConsole:
> 
> def run_python():
> 	import code import __main__ locals = __main__.__dict__ x =
> 	code.InteractiveConsole(locals) x.interact("")
> 
> Shouldn't this have the same namespace as my main interpreter?
> 
> If not, how can I get my main interp namespace propagated down to my
> InteractiveConsole?
> 
> Are there any detailed docs on this?  I've read all the ones I can find.
> 
> Thanks, Bruce.
> 
> 
> Here's my test:
> 
> Python 2.0 (#42, Mar 15 2001, 13:24:46) 
> [GCC 2.95.3 20010219 (prerelease)] on linux2
> Type "copyright", "credits" or "license" for more information.
> 
>>>> from CLI import *	<--run my CLI app
> 
> k->  k-> python 		<-- command to start subshell, calls run_python, above
>>>> dir()		<-- this is all that's defined
> ['__builtins__', '__doc__', '__name__', 'atexit', 'histfile', 'os',
> 'readline', 'rlcompleter', 'savehist', 'sys']
>>>> 
>>>> 			<-- exit subshell
> k-> 			<-- exit app
>>>> dir()		<-- top level, this is what I want in my subshell:
> ['CommandException', 'KCompleter', 'Kcmd', 'Port', 'Zone',
> '__builtins__', '__doc__', '__name__', 'atexit', 'basedir', 'cNode',
> 'cOpt', 'cType', 'cli', 'cmd', 'cmds', 'copy', 'ctree', 'dprintf',
> 'dprintf_exception', 'dprintf_init', 'dprintf_level', 'histfile',
> 'histname', 'kcmd', 'kcompl', 'kcomplMode', 'kcompleter', 'kinterp',
> 'kuser', 'mType', 'main', 'modules', 'nType', 'os', 'port', 're',
> 'readline', 'register_new_command', 'rights', 'rlcompleter', 'savehist',
> 'sl', 'string', 'sys', 'tokens', 'topcmds', 'traceback', 'types',
> 'util']



More information about the Python-list mailing list