python -i (interactive environment)

Joe JoeSalmeri at hotmail.com
Tue Mar 8 11:32:57 EST 2005


Isn't this a bug?

Here's the test program:

import code

def test_func():
    lv = 1
    print '\n\nBEFORE lv: %s\n' % (lv)
    code.interact(local=locals())
    print '\n\nAFTER  lv: %s\n' % (lv)
    return

test_func()

gv = 1
print '\n\nBEFORE gv: %s\n' % (gv)
code.interact(local=locals())
print '\n\nAFTER  gv: %s\n' % (gv)

Here's the output and interactive session:



BEFORE lv: 1

Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> lv = 2
>>> print lv
2
>>> ^Z



AFTER  lv: 1



BEFORE gv: 1

Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> gv = 2
>>> print gv
2
>>> ^Z



AFTER  gv: 2

In the case of code.interact being called inside the function, the locals 
were available to the interactive environment but changes did not stick when 
you returned back the function. (started as lv=1 changed to lv=2 in 
interactive session, back to lv=1 in function)  Since you are still in the 
function and since code.interact used the same local environment why didn't 
the change stick until testfunc ended?

When code.interact was called from the outside the function (globals() == 
locals()) the changes stuck. (started as gv=1, changed to gv=2 in 
interactive session, stuck as gv=2 back in main).





"Steve Holden" <steve at holdenweb.com> wrote in message 
news:mailman.42.1110224680.1799.python-list at python.org...
> Michael Hoffman wrote:
>> Joe wrote:
>>
>>> I want the script to decide whether to fall back to the interactive 
>>> prompt. You solution makes it ALWAYS fall back to the interactive 
>>> prompt.
>>
>>
>> Actually, using sys.exit() means the program can exit even if python -i
>> is used.
>>
>> You can use:
>>
>> import code
>> code.interact()
>>
>> which emulates the interactive prompt.
>
> Unfortunately it does so in an entirely new namespace, thereby losing the 
> advantage of -i - namely, that you can investigate the program's namespace 
> after it's terminated.
>
> regards
>  Steve
> 





More information about the Python-list mailing list